Hello,
I have a few functions that belong to the class.
I want to have these in a table from which I will use the value to select a stored function that I will then run.
Unfortunately, this does not work in class. What is the reason ?
OOP limitations in Lua ?
function Klas:Circle()
print('Circle')
end
.
.
.
function Klas:run(value)
local gen = {self:Circle, self:Triangle, self:Square}
gen[value]()
end
If the function is outside the class, there is no problem. I’m just interested in this.
For fun I through your question into chatgpt, not sure it makes sense though, but here is the answer:
" It seems like you’re trying to create a class Klas with methods Circle, Triangle, and Square, and then you want to have a method run that selects and executes one of these methods based on a given value. However, you’re encountering an issue when trying to call these methods from the gen table.
The problem is that when you call gen[value](), the self reference is not passed correctly, which is causing the issue. When you call self:Circle() directly within the class, Lua knows to pass the self reference automatically. However, when you try to call it from the gen table, it doesn’t have the self reference.
One way to work around this is to bind the methods to the instance of the class when you create the gen table. You can do this using a technique often called “method binding”. Here’s an example:
luaCopy code
function Klas:Circle()
print('Circle')
end
function Klas:Triangle()
print('Triangle')
end
function Klas:Square()
print('Square')
end
function Klas:run(value)
local gen = {self.Circle, self.Triangle, self.Square}
-- Bind methods to the current instance
for i, method in ipairs(gen) do
gen[i] = function(...)
return method(self, ...)
end
end
gen[value]()
end
local k = Klas()
k:run(1) -- This will call Circle()
In this example, the methods in the gen table are bound to the current instance of the class using a closure. This way, when you call gen[value](), it will correctly pass the self reference.
Remember, Lua doesn’t have built-in support for classes, so you have to handle these things manually."