3

so i have a lua file analogous to this:

x = { __index = x}

constructor = function()
    local o = {}
    return setmetatable(o,x)
end

function x:print()
    print("hello world")
end

i type the following into the interpretr:

dofile "file.lua"
a = constructor()
a:print() --error attempt to call method 'print' (a nil value)

dofile "file.lua"
a = constructor()
a:print() -- hello world

the method works the second time i import the file but not the first. why is this? I have tried changing the order (putting the constructor function last) and it was the same.

phat pat
  • 31
  • 1

1 Answers1

3

The first time x is nil. It gets defined and then used the second time.

You need to write x = {}; x.__index = x.

lhf
  • 70,581
  • 9
  • 108
  • 149