LUA indexed table access via named constants

140 Views Asked by At

I am using LUA as embedded language on a µC project, so the ressources are limited. To save some cycles and memory I do always only indexed based table access (table[1]) instead og hash-based access (table.someMeaning = 1). This saves a lot of memory.

The clear drawback of this is approach are the magic numbers thrughtout the code.

A Cpp-like preprocessor would help here to replace the number with named-constants.

Is there a good way to achieve this? A preprocessor in LUA itself, loading the script and editing the chunk and then loading it would be a variant, but I think this exhausts the ressources in the first place ...

1

There are 1 best solutions below

3
Robert On

So, I found a simple solution: write your own preprocessor in Lua! It's probably the most easy thing to do.

First, define your symbols globally:

MySymbols = {
  FIELD_1 = 1,
  FIELD_2 = 2,
  FIELD_3 = 3,
}

Then you write your preprocessing function, which basically just replace the strings from MySymbols by their value.

function Preprocess (FilenameIn, FilenameOut)
  local FileIn     = io.open(FilenameIn, "r")
  local FileString = FileIn:read("*a") 

  for Name, Value in pairs(MySymbols) do
    FileString = FileString:gsub(Name, Value)
  end

  FileIn:close()

  local FileOut = io.open(FilenameOut, "w")
  FileOut:write(FileString)
  FileOut:close()
end

Then, if you try with this input file test.txt:

TEST FIELD_1
TEST FIELD_2
TEST FIELD_3

And call the following function:

Preprocess("test.txt", "test-out.lua")

You will get the fantastic output file:

TEST  1
TEST  2
TEST  3

I let you the joy to integrate it with your scripts/toolchain.

If you want to avoid attributing the number manually, you could just add a wonderful closure:

function MakeCounter ()
  local Count = 0
  return function ()
    Count = Count + 1
    return Count
  end
end

NewField = MakeCounter()

MySymbols = {
  FIELD_1 = NewField(),
  FIELD_2 = NewField(),
  FIELD_3 = NewField()
}