使用来自 Class 的变量继承 LUA Table 和 setmetatable

Inherit LUA Table with variables from Class with setmetatable

我对在 lua 中使用元table、索引和一般 OOP 来“伪造”OOP 的概念还很陌生。

我正在尝试从 LUA 中的对象创建一个实例,它使用 table 中的变量,以便每个实例都有自己的值。 Fighter 模型接缝很常见,所以我试图解释 :-)

FIGHTER = {
    ["id"] = "Fighter",
    ["params"] = {      
        ["route"] = 
        {                                    
            ["points"] = 
            {
                [1] = 
                {
                    ["x"] = wp01x,
                    ["y"] = wp01y,
                    ["speed"] = fighterSpeed,
                    ["task"] = 
                    {
                        ["id"] = "ComboTask",

                    },
                },
            },
        },
    },
}

function FIGHTER:new(t)
    t = t or {}
    setmetatable(t,self)
    self.__index = self
    return t
end

local wp01x = 0.38746345345
local wp01y = 1.39876268723
local fighterSpeed = 123

local test = FIGHTER:new({FIGHTER})

创建 table 时,x、y、速度为零(因此构造时缺少条目)。

使用类似

的方式在构造函数中传递值
self.["Mission"].["params"].["route"].["points"].[1].["speed"] = 99

也不行。

创建此类实例的最佳做法是什么?使用一些预设值并稍后克隆 table?

我稍微修正了你的版本,希望它能让你大开眼界...

FIGHTER = {
    ["id"] = "Fighter",
    ["params"] = {      
        ["route"] = 
        {                                    
            ["points"] = 
            {
                [1] = 
                {
                    ["x"] = 0,
                    ["y"] = 0,
                    ["speed"] = 0,
                    ["task"] = 
                    {
                        ["id"] = "ComboTask",

                    },
                },
            },
        },
    },
}

function FIGHTER:new(t, wpx, wpy, speed)
    t = t or {id = "Fighter", params = {route = {points = {[1] = {x = wpx, y = wpy, fighterSpeed = speed, task = {id = "ComboTask"}}}}}}
    setmetatable(t,self)
    self.__index = self
    return t
end

local wp01x = 0.38746345345
local wp01y = 1.39876268723
local fighterSpeed = 123

-- The t = t or >>{...}<< case
test = FIGHTER:new(_, wp01x, wp01y, fighterSpeed)
-- The t = >>t<< case
test = FIGHTER:new({id = "Fighter", params = {route = {points = {[1] = {x = wp01x, y = wp01y, fighterSpeed = fighterSpeed, task = {id = "ComboTask"}}}}}})