Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there aliasing in lua similar to ruby

Tags:

lua

Can you alias a function (not in a class) in LUA in a similar way to Ruby? In ruby you would do something like this:

alias new_name_for_method method()
def method()
  new_name_for_method() # Call original method then do custom code
  i = 12 # New code
end

I'm asking because I'm developing for a program that uses LUA scripting and I need to override a function that is declared in a default file.

like image 699
Lokiare Avatar asked Oct 16 '25 17:10

Lokiare


2 Answers

In Lua, functions are values, treated like any other value (number, string, table, etc.) You can refer to a function value via as many variables as you like.

In your case:

local oldmethod = method
function method(...)
   oldmethod(...)
   i = 12 -- new code
end

keep in mind that

function method() end

is shorthand for:

method = function() end

function() end just creates a function value, which we assign to the variable method. We could turn around and store that same value in a dozen other variables, or assign a string or number to the method variable. In Lua, variables do not have type, only values do.

More illustration:

print("Hello, World")
donut = print
donut("Hello, World")
t = { foo = { bar = donut } }
t.foo.bar("Hello, World")
assert(t.foo.bar == print) -- same value

FYI, when wrapping a function, if you want its old behavior to be unaffected for now and forever, even if its signature changes, you need to be forward all arguments and return values.

For a pre-hook (new code invoked before the old), this is trivial:

local oldmethod = method
function method(...)
    i = 12 -- new code
    return oldmethod(...)
end

A post-hook (new code invoked after the old) is a bit more expensive; Lua supports multiple return values and we have to store them all, which requires creating a table:

local oldmethod = method
function method(...)
    local return_values = { oldmethod(...) }
    i = 12 -- new code
    return unpack(return_values)
end
like image 138
Mud Avatar answered Oct 18 '25 08:10

Mud


In lua, you can simply override a variable by creating a new function or variable with the same name.

function name_to_override()
    print('hi')
end

If you still want to be able to call the old function:

local old_function = name_to_override

function name_to_override()
    old_function()
    print('hi')
end
like image 27
Jan Berktold Avatar answered Oct 18 '25 08:10

Jan Berktold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!