Using Lua Tables

This forum allows you to share scripts with other Zeus users. Please do not post bug reports, feature requests or questions to this forum, but rather use it exclusively for posting scripts or for the discussion of scripts that have been posted.
Post Reply
jussij
Site Admin
Posts: 2650
Joined: Fri Aug 13, 2004 5:10 pm

Using Lua Tables

Post by jussij »

Using the table feature of Lua it is easy to write a macro that takes a user input string and maps this input to a second string.

For example consider the following mapping.txt text file which maps a key word to a string value:

Code: Select all

return {
  -- Key      Value
  ["for"] = "for (int i = 0; i < 100; ++ 1)\n{\n}",
  ["do"]  = "do\n{\n}\nwhile(i < 0);",
  ["if"]  = "if ()\n{\n}",
}
The following macro will ask the user for a key input, load the above mapping file into an Lua table, search the table for the key provided and insert the value found into the currently writable document:

Code: Select all

function table_list(key_values)
  list = ""

  -- build up a list of the keys in the table
  for key, value in key_values do
    list = list .. key .. "\n"
  end

  return list
end

function key_macro()
  -- macro only works for documents
  local document = is_document()

  -- macro only works for read/write documents.
  local locked = is_read_only()

  if (locked == 1) or (document == 0) then
    message("This macro can only be run with a writable document file.")
    beep()
    return
  end

  -- the default key value
  local nill = ""

  -- ask for a user for a key value
  local key_value = user_input("Key Value:", nill)

  local result = string.len(key_value)

  if result > 0 then
    -- load the key mapping
    key_values = dofile("mapping.txt")

    -- use the key to look for the result
    result = key_values[key_value]

    -- see if anything was found
    if result ~= nil then
      screen_update_disable()

      -- print the result found
      print(result)

      screen_update_enable()
      screen_update()
    else
        message_box(1, "The key: " .. key_value .. "\n\nwas not found in key list:\n\n" .. table_list(key_values), "Key Not Found")
    end
  else
    message("Operation canelled by user.")
  end
end

key_macro() -- run the macro
Cheers Jussi
Post Reply