英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论