Cannot get a Lua function to reference 'self'

2k views Asked by At

I'm trying to create a simple class with a member function that would print out some member values, but I'm getting errors when I try to reference 'self':

attempt to index global 'self' (a nil value)

Here's the script I'm trying to run:

Test = {}

function Test:new()
    T = {}
    setmetatable(T, self)
    self.__index = self
    self.Name = "Test Object"
    return T
end

function Test:printName()
    print("My name is " .. self.Name) -- This causes the error
end

I've also tried self:Name but I get a similar error. What am I doing wrong here?

EDIT:

Forgot to mention that I call the printName() function from C++ code. If I call the function from Lua, it works properly.

The Test object is created in Lua and a callback function is done. The callback is called in C++ like this:

luabridge::LuaRef testObjectRef = ...; // This is populated from Lua, refers to the printName() function
testObjectRef(); // Calls the function

The callback in the script is done like this:

-- in Test:new()
self.Callback = LuaCallback(self.printName)
Helper.setCallback(self.Callback)

The callback itself works fine if I don't try to refer to self. The error comes up only when I try to do that.

2

There are 2 answers

0
manabreak On BEST ANSWER

I managed to fix the problem. I added the self as an extra argument in the listener constructor and passed it as the first parameter to the callback function.

-- in the script
self.Callback = LuaCallback(self, self.printName)
Helper.setCallback(self.Callback)
3
Bartek Banachewicz On

I took your code, added:

local test = Test:new()
test:printName()

It gives me the correct output.

My name is Test Object

If you're calling it via C API, you have to remember to manually push the self argument onto the stack. Remember that:

obj:fun() ~ obj.fun(obj)