2

This is my first time using metatables, I did a simple script to test in Lua demo but it always give me "attempt to call method 'rename' (a nil value)", why?

peds = {}

function peds.new ( name )
    local tb = { name = name }
    setmetatable ( tb, { __index = peds } )
    return tb
end

function peds.rename ( name )
    self.name = name
    return self.name == name
end

local ped = peds.new ( "max" )
ped:rename ( "randomname" )
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
t3wz
  • 23
  • 2

1 Answers1

4

There's two (possible) problems in your code, depending on how you are setting things up.

If you are just typing the above into a REPL, then when you declare local ped = ... it immediately goes out of scope and becomes inaccessible. So the expression ped:rename is invalid, although it should report "ped is nil" not "rename is nil".

If you are saving the above to a script and loading it using load_file or something, you will still get a problem, because this function signature isn't right:

function peds.rename ( name )

should be:

function peds.rename ( self, name )

Similar to how it works in C++, in lua, when you make an object method, you have to take the hidden self parameter first, and when you call ped:rename( "random name" ) that's just syntactic sugar for ped.rename(ped, "random_name"). If the self parameter doesn't exist then it's not going to work, or may even say "function not found / rename is nil" because the signatures don't match up.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87
  • 2
    Note that `function peds.rename(self, name)` can also be written as `function peds:rename(name)`. ie, `:` syntax can be used for both method calls and method declarations. – tehtmi Aug 27 '15 at 09:45