【问题标题】:Table.insert table argument recognized as stringTable.insert 表参数被识别为字符串
【发布时间】:2020-03-27 04:31:02
【问题描述】:
bulletsPlayer1 = { 
   Pistol = {},
   Shotgun = {}
}

bulletsPlayer2 = { 
   Pistol = {},
   Shotgun = {}
}

我有这些表格,我有这个功能来创建项目符号:

function createBullet(x, y, angle, speed, weapon, player)
   local directionx = speed * math.cos(angle)
   local directiony = speed * math.sin(angle)

   table.insert(
      "bulletsPlayer"..player.."."..weapon,
      {
         positionx = x,
         positiony = y,
         directionx = directionx,
         directiony= directiony,
         speed = speed
      }
   )
end

例如,如果我这样调用这个函数

createBullet(100,100,0,300,'Shotgun',1)

我收到此错误:

shooting.lua:77: 'insert' 的参数 #1 错误(应为表,得到字符串)

如何让我的代码将 table.insert() 的第一个参数识别为我的表而不是字符串?

【问题讨论】:

    标签: string lua arguments concatenation


    【解决方案1】:

    "bulletsPlayer"..player.."." ..weapon 是一个字符串。因此,错误消息正是您所期望的。

    你不能只从字符串中构建变量名,然后希望 Lua 知道该怎么做。

    由于bulletsPlayer1 是一个全局表值,您可以通过全局环境访问它。

    _ENV["bulletsPlayer"..player][weapon]
    

    参考https://www.lua.org/manual/5.3/manual.html#2.2

    但通常你只是使用表键来获得你需要的东西。您不会从字符串构建全局名称。

    那么你应该有类似的东西:

    local players{[1] = {bullets = {shotgun = 20, pistol = 9}}}
    

    但是,如果您打算这样做,您可能想阅读一些有关 Lua 中 OOP 的内容。如果子弹是玩家的属性,为什么不将该信息存储在玩家对象中。元表也可以让您的生活更轻松。

    【讨论】:

      【解决方案2】:

      如何让我的代码将 table.insert() 的第一个参数识别为我的表而不是字符串?

      这……不是 Lua 的工作方式。字符串就是字符串,表就是表。如果您想按数字索引您的玩家,请将它们存储在一个表格中:

      local bulletsPlayer = {
         {
            Pistol = {},
            Shotgun = {}
         };
         {
            Pistol = {},
            Shotgun = {}
         };
      }
      

      然后你可以用这样的数字来索引它

      bulletsPlayer[1]["shotgun"]
      

      【讨论】:

      • bulletsPlayer[1]["Shotgun"] 大写 S
      猜你喜欢
      • 2017-05-23
      • 1970-01-01
      • 2013-02-13
      • 2022-06-16
      • 2017-02-12
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多