Search code examples
methodsluaauto-incrementpass-by-referencemeta-method

make lua method that can directly change arguments


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 .


Solution

  • 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.)