223 posts
Location
Minecraft in Minecraft in Minecraft in ComputerCraft... in Minecraft
Posted 20 August 2015 - 09: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…
Edited on 20 August 2015 - 07:50 AM
656 posts
Posted 20 August 2015 - 09:57 AM
2 options:
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.
223 posts
Location
Minecraft in Minecraft in Minecraft in ComputerCraft... in Minecraft
Posted 20 August 2015 - 10:05 AM
2 options:
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 on 20 August 2015 - 08:17 AM
656 posts
Posted 20 August 2015 - 11:38 AM
Ah, sorry, I misunderstood your question.
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 on 20 August 2015 - 09:39 AM
7083 posts
Location
Tasmania (AU)
Posted 20 August 2015 - 12:17 PM
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).