This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
LewisTehMinerz's profile picture

How would you create sub-functions?

Started by LewisTehMinerz, 20 August 2015 - 07:50 AM
LewisTehMinerz #1
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
flaghacker #2
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.
LewisTehMinerz #3
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
flaghacker #4
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
Bomb Bloke #5
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).