Greetings! Is there a way to turn the name of a function into a form that can be passed to something else to then be called? In a nut shell, can function names be variables? This would save a boat load of time.
An example of when you’d use this is, you have a menu class that needs to play button press sounds at the correct time and volume. You could have the menu class play the sound and the owner of the class tell every single menu to change its volume when the volume changes. OR you could give the all of the menu classes (in its parameters) a function to call that plays the sound were the sound has easy access to the volume and mute settings.
@Goatboy76 Variables and functions differ between every programming language, so it’s hard to say. As for classes, yes, they are also variables. They’re actually metatables, which are sort of an extension upon normal tables. Metatables are pretty much the same as normal tables, except they can have functions that integrate with the Lua language, such as a function to be called when you “call” the variable as if it were a function, or even adding two values together.
Here’s the Lua code for the class() function, if it helps you understand:
-- Class.lua
-- Compatible with Lua 5.1 (not 5.0).
function class(base)
local c = {} -- a new class instance
if type(base) == 'table' then
-- our new class is a shallow copy of the base class!
for i,v in pairs(base) do
c[i] = v
end
c._base = base
end
-- the class will be the metatable for all its objects,
-- and they will look up their methods in it.
c.__index = c
-- expose a constructor which can be called by <classname>(<args>)
local mt = {}
mt.__call = function(class_tbl, ...)
local obj = {}
setmetatable(obj,c)
if class_tbl.init then
class_tbl.init(obj,...)
else
-- make sure that any stuff from the base class is initialized!
if base and base.init then
base.init(obj, ...)
end
end
return obj
end
c.is_a = function(self, klass)
local m = getmetatable(self)
while m do
if m == klass then return true end
m = m._base
end
return false
end
setmetatable(c, mt)
return c
end
You might want to study these threads. They are about callbacks, but a callback is just a variable that contains a function address, which is what you need.
@Goatboy76, Lua has one of the best designs with regard to functions. Many high-level mainstream languages, including C++, Java, Javascript, and Python have weaker support for functions. If you are interested in this, i would very much recommend “Programming in Lua” book by Roberto Ierusalimschy. He explains functions and closures very well. (It’s a great book in many other respects too.)
In general, no. You might be able to do this for functions written in Lua, via some trick using debug library (or if you had saved the source explicitly into function’s metatable), but for C-functions it’s pretty much impossible.