Reputation: 5156
I'm getting an error with Lua (standard interprteter) and I can't find the source of the problem. I am trying to create something that resembles an enum from languages like Java, C#, etc. The current code that I have to define the enum standards is this:
enum = {
new = function (self, ...)
local o = {};
setmetatable(o, self);
self.__index = self;
for k,v in args do -- THIS LINE IS GIVING THE ERROR
self[v] = 2^k;
end
table.sort(self, function(a,b) if a>b then return true; else return false; end end)
return o;
end,
sum = function (self, ...)
local s
for k,v in args do
s = s+self[v];
end
end,
expand = function (self, number)
indices = {};
for k,v in ipairs(self) do
if v < number then
table.append(k);
number = number-v;
end
end
return unpack(indices);
end
}
The error appears in the new
function, in the loop statement (not the statement inside it). What can be the cause of this? I'm not "calling" the values, just referencing them.
I also tried replacing 2^k
with math.pow(2,k)
, so it's not the math, either.
I run the following code to test the script:
myEnum = enum:new("a","b","c");
I should note that the error simply says what is on the title, no variable name or anything.
Upvotes: 0
Views: 2215
Reputation: 5818
Firstly, a for loop of the type for k,v in...
expects to take an iterator function, not a table; secondly, args
is unset when you refer to it. If you want to loop over the varargs to the function, use for k,v in ipairs({...})
.
Note that if one of the varargs is nil, iterating with ipairs
may stop at the nil, and iterating with pairs
isn't guaranteed to return the varargs in the same order they were passed. If this is a problem, a workaround can be found here.
Upvotes: 2