簡體   English   中英

嘗試調用方法'func'(零值)

[英]attempt to call method 'func' (a nil value)

無論我如何接近Lua,我都會遇到這個錯誤,所以我不能理解繼承語言的東西:

嘗試調用方法'func'(零值)

我已經在這里看過幾次這個錯誤,但這個問題對我來說似乎並不清楚。

這是我的模塊:
actor.lua

Actor = {
    x = 0,
    mt = {},

    new = function()
        local new_actor = {}
        new_actor.x = Actor.x
        new_actor.mt = Actor.mt
        return new_actor
    end,

    test = function(self, a, b)
        print(a, b)
    end
}

我正在使用Löve。
main.lua

require "game/actor"
local a = Actor:new() --works fine

function love.load()
    a.x = 10
    print(a.x) --output: 10
    a:test(11, 12) --error: attempt to call method 'test' (a nil value)
end

我也不確定何時在模塊中使用之前的樣式是合適的。

Actor = {
    x = 0
}
Actor.mt = {}

function Actor.new()
    print(42)
end

我老實說不確定什么比另一個更正確,但考慮到我遇到一個簡單的錯誤,可能有些東西我完全錯過了?

看起來你正試圖用一種由metatables組成的類。 你基本上需要分配new_actor用的元表Actor.mt (恢復問題:當你索引new_actor時,在這種情況下你沒有索引Actor

setmetatable(new_actor, Actor.mt);

即使添加了元表,也只有在將元“__index”事件索引到包含類方法/值的表時才會有效,在這種情況下:

Actor.mt = {
    __index = Actor
};

我建議將類方法/值移動到一個新表中,如Actor.prototypeActor.fn等...避免沖突:

Actor.fn = {
    test = function(self, a, b)
        print(a, b)
    end
};

Actor.mt = {
    __index = Actor.fn
};

有關Lua 5.3手冊中的元數據的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM