5242 Bora
5242 Bora

Reputation: 17

lua - differece of : and . when define function?

hope you having great day , i'm test some stuff with lua, and i got some error

i have this codes in Object.lua

local Object = {name = "Object"}
Object.__index = Object

function Object.new()
  local t = setmetatable({}, Object)
  return t
end

function Object:keys(table)
local keyset={}
local n=0

for k,v in pairs(table) do
  n=n+1
  keyset[n]=k
end
return keyset
end

return Object

and i call Object.keys in "Other" script like this

local Object = require("lua.app.common.utils.Object")

local t = {
[1] = a,
[2] = b,
[3]= c
}
Object.keys(t)

and this cause error with Exception has occurred: bad argument #1 to 'for iterator' (table expected, got nil), because the parameter 'table' is passed as nil ( i don't know why thuogh debug mode just says its a nil)

on the other hand, if i fix object.keys(table) to object:keys(table), everything works fine, why this error happening?

Upvotes: 0

Views: 116

Answers (1)

Tony
Tony

Reputation: 10347

Declaring the method keys with a colon adds an implicit self parameter as the first argument which requires you to call the method in the same way, using the colon.

Calling the method with the period notation expects you to supply the self parameter but because you only pass in t this is interpreted as self and then nil is added for your table parameter.

Declaring the method with a colon you actually have this

function Object:keys(self, table)

but calling it with the period means you have done this

Object.keys(t, nil)

hence the "table expected, got nil" error

Upvotes: 3

Related Questions