Edited by LewisTehMinerz, 20 August 2015 - 08:50 AM.
How would you create sub-functions?
Started by LewisTehMinerz, Aug 20 2015 08:50 AM
4 replies to this topic
#1
Posted 20 August 2015 - 08:50 AM
How would you create sub-functions? (Like m:testing() but you need to define m first like m = blah.create()) I've seemed to completely forgot...
#3
Posted 20 August 2015 - 09:05 AM
flaghacker, on 20 August 2015 - 08:57 AM, said:
2 options:
two ways to caal them too:
More info about it and related stuff can be found here.
function a.foo(self) print(self.something) end
function a:foo() print(self.something) end
two ways to caal them too:
a.foo(a) a:foo()
More info about it and related stuff can be found here.
I would like around 3 functions coming from 1 function. (create). If I try to do m = multi.create(), m is still nil.
Edited by LewisTehMinerz, 20 August 2015 - 09:17 AM.
#4
Posted 20 August 2015 - 10:38 AM
Ah, sorry, I misunderstood your question.
The trick is to return a table containing functions and
possibly values.
You can make the code more efficient using metatables, as explained here. I'd recommend reading the previous link I posted to, it's the introduction.
The trick is to return a table containing functions and
possibly values.
function createHuman (name)
local h = {}
h.name = name
h:sayHi = function ()
print ("hi, I'm " .. self.name)
end
return h
end
local bob = createHuman ("bob")
bob:sayHi () --hi, I'm bob
You can make the code more efficient using metatables, as explained here. I'd recommend reading the previous link I posted to, it's the introduction.
Edited by flaghacker, 20 August 2015 - 10:39 AM.
#5
Posted 20 August 2015 - 11:17 AM
The one "catch" to using metatables (directly, at least) is that the resulting object needs to use colon notation to call the functions, as opposed to dot notation. This doesn't really "matter", but since colon notation is uncommon, coders seem to avoid it.
(I suspect colon notation may execute slower, too, given that Dan goes out of his way not to use it on string objects. Haven't tested it to see if that's the case.)
The window (returns dot-notation-using objects) and vector (returns colon-notation-using objects) APIs are great examples to read through. Using metatables generally nessatates colon-notation objects, but you can translate them before returning them (eg, as Gopher's redirect API does).
(I suspect colon notation may execute slower, too, given that Dan goes out of his way not to use it on string objects. Haven't tested it to see if that's the case.)
The window (returns dot-notation-using objects) and vector (returns colon-notation-using objects) APIs are great examples to read through. Using metatables generally nessatates colon-notation objects, but you can translate them before returning them (eg, as Gopher's redirect API does).
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users











