【问题标题】:Search Results lua - Attempt to index global 'self' (a nil value)搜索结果 lua - 尝试索引全局“自我”(零值)
【发布时间】:2017-12-20 05:09:38
【问题描述】:

我正在运行此代码,希望让我的敌人每 5 秒不断生成,但我只是不断收到“尝试索引全局 'self'(一个 nil 值)”。这是在我的游戏文件中,表格来自我的敌人文件。任何帮助表示赞赏。

timer = timer + dt
if timer >= 5 then 
table.insert(self.enemies, enemy)
timer = timer - 5
end

【问题讨论】:

  • 我不做 Lua 所以不要期待太多,但是你试过table:insert(self:enemies, enemy) 吗?我是从 here 那里得到的
  • 如果enemies是全局变量,那么试试table.insert(enemies, enemy)

标签: lua love2d


【解决方案1】:

self 在函数内部有效,其中self 是显式指定的参数或使用冒号运算符定义的函数(如function foo:bar()),因为在这种情况下它将作为隐藏参数提供。

在您的情况下,这两种情况都不满足,self 被视为未定义的全局变量。

有关正确使用的详细信息和示例,请参阅Object-Oriented Programming chapter in Programming in Lua

【讨论】:

  • 谢谢,你有什么办法或其他方法让我的敌人不断生成吗?
【解决方案2】:

我可以看到一些错误的地方。我将解释一种正确的方法,您可以将其与您的设置方式进行比较。

在你的敌人文件中(我假设它被称为enemy.lua),应该有一个包含一些东西的表:

  1. 包含敌人列表的表格(确保在文件末尾返回!)
  2. 创建新敌人的函数

它可能看起来像这样:

local enemies = { }    -- table to export

enemies.list = { }     -- list of entities

function enemies.new()
    local new_entity = { }

    new_entity.x = 0        -- set entity coordinates
    new_entity.y = 0        

    -- set any another entity information, like sprites, health, etc.

    return new_entity
end

return enemies         -- make this table available to other files through require

然后,你将它导入到 main.lua 中:

local enemies = require "enemies"

这将使 enemies.listenemies.new 在你的 main.lua 中可用。然后你的 table.insert 就变成了

table.insert(enemies.list, enemies.new())

基本上,您的主要错误是试图在不使用require 的情况下访问另一个文件中的内容。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2014-01-21
    相关资源
    最近更新 更多