在Lua中,如何在一个语句中定义稀疏数组?

huangapple go评论53阅读模式
英文:

How can I define a sparse array in one statement in lua

问题

作为示例,我正在做这个

local Bool = {} 
Bool [false]='OFF' 
Bool [true]='ON'

我以为这会起作用,但事实并非如此

local Bool = {false='OFF', true='ON'}

如何在一条语句中定义它?
英文:

As an example, I am doing this

local Bool = {} 
Bool [false]='OFF' 
Bool [true]='ON'

I thought this would work, but it doesn't

local Bool = {false='OFF', true='ON'}

How can I define it in one statement?

答案1

得分: 4

你尝试使用的表示法仅在索引可以写成标识符时有效,因此只能使用字母数字和下划线,对于其他值,如数字、奇怪的字符串、布尔值、表格或函数,你需要使用

myTable = {[false] = "一些值", [-1/12] = 0}

你需要将索引括在方括号中。

顺便说一句,这不是多维数组。

英文:

The notation you are trying to use only works when the indices can be written as identifiers, so alphanumeric + underscore, for any other values, numbers, weird strings, booleans, tables or functions, you want to use

myTable = {[false] = "some value", [-1/12] = 0}

You need to enclose indices in square brackets.

Btw that's not a multidimensional array

huangapple
  • 本文由 发表于 2023年5月10日 20:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定