我正在尝试修改我在这个视频中找到的示例类,使其更加流畅易用。希望我的注释足够清楚地解释了我想要实现的目标。问题是当我尝试使用数据表时,它会给我一个错误:lua: class example.lua:7: attempt to index field 'data' (a nil value)。
我猜这意味着数组没有被正确地传递到函数中,但我不知道为什么。我非常菜鸟Lua。
以下是我的代码:
我猜这意味着数组没有被正确地传递到函数中,但我不知道为什么。我非常菜鸟Lua。
以下是我的代码:
local enemy = {}; --enemy class table
function enemy:New(data)
local object = {}; --table to store all of data within class
local len = # data --get length of passed table
for i = 1, len, 2 do --loop to input all data from passed table into object table
object.data[i] = data[i + 1];
end
function object:getData(choice) --function that allows us to retrieve data from the class
return self[choice];
end
return object; --return class data table so we can create objects using the class
end
local monsterdata = {"name", "monster", "x", 64, "y", 128, "hp", 4}; --table containing data of monster. keys are odd numbered, values to those keys are even numbered
local monster = enemy:New(monsterdata); --create a object using the class
local test = monster:getData("x"); --set variable to a value with the getData function
print(test);