Log In  

Is there any way to do the following?

t = {
  "key 1" = "foofoo",
  "key 2" = "barbar"

We can't use quoted keys when defining a table, but we can use them when adding elements.

t = {}
t["key 1"] = "foofoo"
t["key 2"] = "barbar"

Is this "just how things are?" because it would really be beneficial to be able to do it all inline and build out a complex table structure without having to isolate out special cases and insert them as a separate sequence of setter calls.

(the example above uses spaces in the key intentionally, where it might be a substring paired with its substitution or maybe I just want to make it very clear in the definition that some of the keys represent specific words, like vocabulary words; don't get me wrong, I know lots of workarounds, but sometimes the workarounds are a drag, especially when it looks like we're so close to just having a simple way of doing things)

Clarification here. The first example fails to compile with a "missing {" error when trying to use inline quoted keys. @fred72 shows below that wrapping those in square brackets allows for using the quoted key without resorting to the second method shown.

P#91621 2021-05-07 03:00 ( Edited 2021-05-07 07:55)

table entries must be valid identifier, see: https://www.lua.org/pil/1.3.html
space is not a valid character (nor a digit in first position).
invalid identifiers must be quoted as you found out.
note alternate syntax:

  [« key 1 »]=« blah »

if you are concerned with the token cost, see how you can generate a table with split() using a custom separator.

P#91626 2021-05-07 05:58 ( Edited 2021-05-07 06:00)

The "quoting" isn't the issue I was trying to ask about; sorry if it came off that way. I don't mind the quoting. I was just trying to understand why a quoted identifier isn't allowed in the first format. Your alternate syntax shows what I was missing []

and gets me through the problem of "sometimes a key has an invalid identifier and I just want to keep those exceptional cases together with the rest of the table definition."

Just tried it out and it does what I need (or at least Pico8 isn't yelling at me about
unclosed {

The "build a table from a string with custom separators" trick is used extensively in picocalc, but the new project won't come anywhere near the token/character limits. Thank you.

P#91629 2021-05-07 07:32 ( Edited 2021-05-07 07:35)
:: merwok

Also note that the brackets are needed when using non-string keys:


for k,v in pairs(tbl) do

So basically, '{ [key]=value }' is the regular way of defining a table, and '{ key=value }' is the special shortcut for string keys.

P#91637 2021-05-07 14:35 ( Edited 2021-05-07 14:36)

@merwork OK, that makes a lot of sense about
{key = value}

being a convenience to the other way of writing it. That resolves my confusion entirely.

P#91668 2021-05-08 00:55

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2022-08-17 19:05:51 | 0.049s | Q:16