In my game i use a tilemap to create the worldmap. The tile choosen depends on the terrain type and the 8 neighbour terrains. The only interesting question was: The neighbour is the same terrain type as the center? I created a Mask of 8 bits for each neighbour. This was easy and later i figured out, i have to test for rivers in neighbour squares. I changed the mask so string type and used "0|1|R" as flags in the mask string. All working fine.
Now i try to improve speed by going back to integer keys. To handle the rivers on top/left/right/bottom i need 4 more bits in the integer key... All fine.
Now the task: I come in with 8 char strings like "0R0111R0". I need to copy the positions 2,4,5,7 to the left side of the string ( a 12 char string now). The 4 leftmost chars become "R"->"1" or 0. Finally the 4 orginal "R"s need to become replaced by "0".
Now i have a nice string with a binary number, i can give to tonumber().
My working solution is:
It works but i am shure, it is not the best solution( and completely unoptimized: eg. replacement list should be predefined outside the function). This function may become called 2400 times while game starts up.local function idx2i(key)
return tonumber(
key:gsub("([01])([01R])([01])([01R])([01R])([01])([01R])([01])", "%2%4%5%7%1%2%3%4%5%6%7%8")
:gsub("(.)", {["0"] = "0",["1"]="0",R="1"}, 4)
:gsub("R", "0"),
2
);
end;
Any better solutions will make me very happy