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

What is colon notation?

Started by Konlab, 17 May 2014 - 09:02 AM
Konlab #1
Posted 17 May 2014 - 11:02 AM
What is colon notation and how to use?
Lignum #2
Posted 17 May 2014 - 11:21 AM

local aString = "hello"
aString:match("ll")

Here, the string match call, which uses the colon notation, will translate to:


string.match(aString, "ll")

It means, whenever a function, which is inside a table, is called the table will be passed as the first argument so that the table can access itself.
theoriginalbit #3
Posted 17 May 2014 - 11:44 AM
it is just syntactical sugar. since if you make your own object it may look like this

local someObj = newObj()

--# ugly
someObj.foo(someObj, "bar")
--# nice
someObj:foo("bar")
Yevano #4
Posted 17 May 2014 - 09:20 PM
Additionally, the other side of the call can look like this


function Proto:doStuff(x, y)
	return self.z * (x + y)
end

Usually, Proto would be a "prototype" which contains your methods. When you want an instance to inherit those methods, you set the metamethod __index to the prototype table.


local mt = { __index = Proto }
local obj = { z = 5 }
setmetatable(obj, mt)


When you do this, you're telling Lua to search inside Proto for any keys that aren't found in obj. So when you do this:


obj:doStuff(5, 7)


It's like calling Proto.doStuff(obj, 5, 7) (Remember that obj is given as the first parameter implicitly when you use the colon syntax). The reason for doing all this is that now you can make as many objects as instances of Proto as you want, and they'll all be able to call the methods you made in Proto.


local objects = { }
for i = 1, 10 do
	local obj = { }
	setmetatable(obj, mt)
	objects[i] = obj
end
print(objects[4]:doStuff(4, 5))
Edited on 17 May 2014 - 07:22 PM