Difference between . and : in Lua programming

LuaServer Side ProgrammingProgramming

The .(dot) operator in Lua is used to invoke the method of an object, and it is a widely used operator in Lua.

The :(colon) operator in Lua is used when you want to pass an invisible parameter to the method of an object that you are calling.

Let’s consider an example where we will have an object in which two functions are present and we will try to access these functions, first by making use of the dot operator and secondly by making use of the colon operator.

Example

Consider the example shown below −

Live Demo

returnX = {foo = function(x,y) return x end, bar = function(x,y) return y end, }
ans = returnX.foo(10,11)
print(ans)
ans = returnX.bar(10,11)
print(ans)

In the above example, we make use of the dot operator only, and the foo function will return us the first argument that was passed to it, and the bar function will return us the second argument that we passed to it.

Output

10
11

Now, let’s make use of the colon operator instead of the dot operator as in the previous example.

Example

Consider the example shown below −

Live Demo

returnX = {foo = function(x,y) return x end, bar = function(x,y) return y end, }
ans = returnX:foo(10,11)
print(ans)
ans = returnX:bar(10,11)
print(ans)

Output

table: 0x232c910
10

Wait, what? How’s the output an address and 10. Let me explain, when we use the colon(:) operator what actually happens is that instead of calling

ans = returnX:foo(10,11)

what gets called is −

ans = returnX.foo(returnX,10,11)

and hence we get the output as an address, and so in the second case when we call returnX:bar(10,11) the second argument will be 10 and that’s what we get.

Published on 20-Jul-2021 14:05:47