Use string indices with colon ( lua programming)

I am learning the lua programming from a online book. It talks about string indices for an array

If the indices are strings, you can create a single index concatenating both indices with a character in between to separate them. For instance, you can index a matrix m with string indices s and t with the code m[s..':'..t], provided that both s and t do not contain colons (otherwise, pairs like ("a:", "b") and ("a", ":b") would collapse into a single index "a::b"). When in doubt, you can use a control character like `\0ยด to separate the indices.

https://www.lua.org/pil/11.2.html

I don't understand what is wrong with index "a::b". What is the difference between "a:b" and "a::b". What's the trick behind it?

1 answer

  • answered 2018-01-12 02:56 Julian

    What the documentation you linked is describing, is away to represent a multidimensional matrix in a single dimensional table. After giving an example of how you can do this with number indices:

    mt = {}          -- create the matrix
    for i=1,N do
      for j=1,M do
        mt[i*M + j] = 0
      end
    end
    

    they describe a way to do the same thing with strings: "If the indices are strings, you can create a single index concatenating both indices with a character in between to separate them." A code snippet that would fit the description would look like:

    str_idxs = {"foo", "bar", "baz"} -- table of the string indices
    mt = {} -- matrix
    for 1,N do
      for 1,M do
        mt[str_idxs[N] .. ":" .. str_idxs[M]] = 0
      end
    end
    
    print(mt["foo:bar"]) -- 0
    print(mt["foo" .. ":" .. "bar"]) -- 0
    print(mt["foo::bar"]) -- nil
    

    As you can see in this example there is nothing special about the ":" character, you can choose any string to be a separator (including "::" if you really wanted). The reason why "foo::bar" is wrong in this case is because you never gave a value to "foo::bar."