Lua中如何将数组作为超长尾参数传递给函数?

2026-04-01 20:101阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计394个文字,预计阅读时间需要2分钟。

Lua中如何将数组作为超长尾参数传递给函数?

我在尝试改进我在this video中找到的示例,以便其更流畅地使用。希望我的评论能解释我正努力完成的事情。我遇到的问题是,当我尝试使用数据表时,它会给我这个错误:lua: clas

我正在尝试改变我在 this video中找到的类示例,以使其更加流线型使用.希望我的评论可以解释我正在努力完成的事情.我遇到的问题是当我尝试使用数据表时它会给我这个错误:lua:class example.lua:7:尝试索引字段’data'(一个零值)

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); 如果你想让对象保存数据,你可能想写

object[data[i]] = data[i + 1];

代替

object.data[i] = data[i + 1];

这样打印的结果是64.

本文共计394个文字,预计阅读时间需要2分钟。

Lua中如何将数组作为超长尾参数传递给函数?

我在尝试改进我在this video中找到的示例,以便其更流畅地使用。希望我的评论能解释我正努力完成的事情。我遇到的问题是,当我尝试使用数据表时,它会给我这个错误:lua: clas

我正在尝试改变我在 this video中找到的类示例,以使其更加流线型使用.希望我的评论可以解释我正在努力完成的事情.我遇到的问题是当我尝试使用数据表时它会给我这个错误:lua:class example.lua:7:尝试索引字段’data'(一个零值)

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); 如果你想让对象保存数据,你可能想写

object[data[i]] = data[i + 1];

代替

object.data[i] = data[i + 1];

这样打印的结果是64.