带字符串键的Lua表不能与数字索引一起使用? [英] Lua table with string keys does not work with number indexing?

查看:560
本文介绍了带字符串键的Lua表不能与数字索引一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Lua的初学者.

我认为使用字符串键将值推到表中也会自动进行数字索引,但是我认为这是错误的.

I thought pushing values to a table using string keys would automatically also do number indexing but I think I was wrong about this.

我的代码:

local t = {}
t.name = "John"
t.age = 30
print("Name : " .. t.name .. "\nAge : " .. t.age)

虽然此代码可以正常工作并显示预期结果,

While this code works fine and prints the expected result,

Name : John
Age : 30

如果我尝试以这种方式打印结果,

If I try to print the result this way,

print("Name : " .. t[1] .. "\nAge : " .. t[2])

我收到以下错误:

lua: main.lua:5: attempt to concatenate a nil value (field '?')
stack traceback:
    main.lua:5: in main chunk
    [C]: in ?

这是否意味着我无法在不知道键字符串的情况下使用带有数字索引的for遍历表?

Does this mean I cannot iterate through the table using for with number indexing without having to know the key strings?

如果是这样,有什么办法可以使双向运行正常?

If so, is there any work around to make the both way work?

推荐答案

向表中添加值也不会像使用索引键一样添加它们.当您使用表中的值时,可以像第一个示例一样使用点符号来访问它们,或者像这样:

Adding values to a table does not also add them as with index keys as well. When you go to use the values in your table you can access them either using the dot notation, as in your first example, or like this:

print("Name : " .. t["name"] .. "\nAge : " .. t["age"])

您可以使用函数pairs遍历表中的键值对,如下所示:

You can iterate over the key value pairs in the table using the function pairs like so:

for k, v in pairs(t) do
    print(k, v)
end

如果要使用索引而不是字符串键,可以按以下方式进行设置:

If you want to use indexes instead of strings keys, you can set it up like this:

local t = {
    "John",
    30,
}
print("Name : " .. t[1].. "\nAge : " .. t[2])

以这种方式进行操作时,表t中的值具有自动分配给每个值的整数索引.如果要一个接一个地遍历它们,可以使用ipairs进行遍历:

When you do it this way, the values in the table t have integer indexes automatically assigned to each value. If you want to iterate over them one by one, you can iterate with ipairs:

for i, v in ipairs(t) do
    print(i, v)
end

这篇关于带字符串键的Lua表不能与数字索引一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆