1

How to create a method like string.gsub(...) in lua ?

I want my function can change Arguments that I pass them to the function.

I know that string and number Type Variables pass by name ( CALL BY VALUE ) in functions,

but I don't know how gsub can change ( apply directly in string type variable ) when we try to use it like s:gsub(...) the s variable change and affected by gsub(...) method !

I want to create a method Inc(...) that when I use it like ex:Inc() the ex ( number var ) Increment by 1 !!!

Help me implement this ... I want that ex variable ( example : ex = 1 ) be numerical (not table)

ex = 1
ex:Inc()
print(ex) -- ex == 2

Thank you .

NIMIX 3
  • 13
  • 2

1 Answers1

2

s:gsub(...) does not affect s, except when you do s=s:gsub(...). Try this:

s="hello"
print(s:gsub("[aeio]","-"))
print(s)

In Lua, all arguments are passed by value. There is no way to change the value of a variable from within a function. (You can change the contents of a table, but not the table itself.)

lhf
  • 70,581
  • 9
  • 108
  • 149
  • cannot force pass a variable by reference ? like & op in c++ accessing the address of variables in memory ! or get help from meta-tables ? in act I want to overload ++ op in lua , but it seems impossible ! – NIMIX 3 Jun 21 '13 at 17:42
  • @NIMIX3 No, there is no `pass by reference` in Lua. – Yu Hao Jun 21 '13 at 17:52