2
votes

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
self.Name is the correct syntax. Lemme run it. - Bartek Banachewicz
Show the code that's used to call it from C++. Are you pushing the self parameter on the stack? (C API doesn't have the notion of : call!) - Bartek Banachewicz
And now you've forgotten to say that you're using luabridge?!!?!. Please do read "about" section again. And I recommend using Sol instead, luabridge is extremely meh in my opinion. - Bartek Banachewicz
@BartekBanachewicz My apologies, I really did think originally it was a problem in just the Lua script. However, I think the choice of luabridge is a personal preference and does not have anything to do with the problem here - suggesting to change to another library is moot as there's already a whole program built upon luabridge. - manabreak
Well, refer to your library docs about calling methods then. - Bartek Banachewicz

2 Answers

1
votes

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)
1
votes

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)