1

Does lua support some way of c-style structs ?

I want to convert something like the following font bitmaps from 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]

[edit] added more data to show non-numeric indices

1 Answer 1

5

The raw idea of a struct is not present in Lua but tables serve a similar purpose.

Using tables:

local font = {
  ["1"] = {0x2, 0x6, 0x2, 0x2, 0x2},
  ["2"] = {0xe, 0x1, 0x6, 0x8, 0xf}
}

This can then be accessed font[letter][x] or font.letter[x]. Bear in mind that Lua arrays are not zero-indexed, so x starts at 1.

If you need a bit more structure then you could use a function to construct the table:

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),
}

but that might be overkill.

Edit: If you want to keep the line in the code you could construct a table like so:

local font = {
  ["1"] = { line = {0x2, 0x6, 0x2, 0x2, 0x2} },
  ["2"] = { line = {0xe, 0x1, 0x6, 0x8, 0xf} }
}

Accessed font[letter].line[x] or font.letter.line[x].
Note that keys which are strings do not need quotes when being defined, aside from numeric strings which is why line is not surrounded by quotation marks wheras "1" and "2" are. (So you could access with code: font[letter]["line"][x])

Sign up to request clarification or add additional context in comments.

6 Comments

"1" = is not valid lua syntax. you'll need to put [] around it.
I'm not sure why you're quoting "1" and "2". [1] = ..., [2] = ... would be clearer. And in fact you don't have to specify the indices, just write local font = { {0x2, 0x6, 0x2, 0x2, 0x2}, {0xe, 0x1, 0x6, 0x8, 0xf} }
Note that font.letter will not work here as letter is "1" or "2".
@Keith I do need the explicit indices, as they are not all numeric ... 0,1,2, ...a,b,c,...A,B,C
@MikeRedrobe: And ["1"] = ... is semantically different from [1] = .... For example, { [1] = "foo", ["1"] = "bar" } gives you a table with two distinct key/value pairs. (There's some potential for confusion here.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.