lua中的结构数组?

Mik*_*obe 1 lua lua-table

lua 是否支持某种方式的 c 风格结构?

我想从 c 转换类似以下字体位图的内容:

struct charmatrix { char c;  int line[5]; };
static charmatrix font[] =
{
  "1", {0x2, 0x6, 0x2, 0x2, 0x2},
  "2", {0xe, 0x1, 0x6, 0x8, 0xf},

  "a" , {0x0, 0x5, 0xb, 0xb, 0x5}

}

font[letter].line[x]
Run Code Online (Sandbox Code Playgroud)

[编辑] 添加了更多数据以显示非数字索引

JWT*_*JWT 5

Lua 中不存在结构的原始概念,但表也有类似的用途。

使用表格:

local font = {
  ["1"] = {0x2, 0x6, 0x2, 0x2, 0x2},
  ["2"] = {0xe, 0x1, 0x6, 0x8, 0xf}
}
Run Code Online (Sandbox Code Playgroud)

然后可以访问font[letter][x]font.letter[x]。请记住,Lua 数组不是零索引的,因此 x 从 1 开始。

如果你需要更多的结构,那么你可以使用一个函数来构造表:

local function charmatrix(c, l1, l2, l3, l4, l5)
  return {[c] = { l1, l2, l3, l4, l5 }}
end

local font = {
  charmatrix("1", 0x2, 0x6, 0x2, 0x2, 0x2),
  charmatrix("2", 0xe, 0x1, 0x6, 0x8, 0xf),
}
Run Code Online (Sandbox Code Playgroud)

但这可能有点矫枉过正。

编辑:如果你想保留line在代码中,你可以像这样构造一个表:

local font = {
  ["1"] = { line = {0x2, 0x6, 0x2, 0x2, 0x2} },
  ["2"] = { line = {0xe, 0x1, 0x6, 0x8, 0xf} }
}
Run Code Online (Sandbox Code Playgroud)

访问font[letter].line[x]font.letter.line[x]
请注意,作为字符串的键在定义时不需要引号,除了数字字符串之外,这就是为什么line不用引号 wheras"1""2"are 的原因。(所以你可以使用代码访问:font[letter]["line"][x]

  • @Keith我确实需要显式索引,因为它们并不都是数字... 0,1,2, ...a,b,c,...A,B,C (2认同)