Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search Lua table values

I have a project that calls for a relational database like structure in an environment where an actual database isn't possible. The language is restricted to Lua, which is far from being my strongest language. I've got a table of tables with a structure like this:

table={
  m:r={
    x=1
    y=1
    displayName="Red"
  }
  m:y={
    x=1
    y=2
    displayName="Yellow"
  }
}

Building, storing and retrieving the table is straightforward enough. Where I'm running into issues is searching it. For the sake of clarity, if I could use SQL I'd do this:

SELECT * FROM table WHERE displayName="Red"

Is there a Lua function that will let me search this way?

like image 776
Sisk Avatar asked Nov 14 '14 21:11

Sisk


People also ask

How do you get values in Lua?

local Table = { "value_1"; "value_2"; "value_3"; "value_4"; }; for Key = 1, #Table, 1 do print(Table[Key]); end; Feel free to ask any questions. Oh, and if you're planning on running this code many times, consider putting local print = print; above your code to define a local variable (they are faster).

What is a table value in Lua?

A table is a Lua data type that can store multiple values including numbers, booleans, strings, functions, and more. Tables are constructed with curly braces ( {} ) as shown here: Code Sample Expected Output Expand.

How do Lua tables work?

Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need. Lua uses tables in all representations including representation of packages.

Why does Lua count from 1?

The major reason that the arrays in Lua are 1-index based is that the language Lua itself is inspired from a language named Sol, which was designed for petroleum engineers that had no formal training in any programming languages or at all in any field of computer science.


1 Answers

The straightforward way is to iterate through all elements and find one that matches your criteria:

local t={
  r={
    x=1,
    y=1,
    displayName="Red",
  },
  y={
    x=1,
    y=2,
    displayName="Yellow",
  },
}
for key, value in pairs(t) do
  if value.displayName == 'Red' then
    print(key)
  end
end

This should print 'r'.

This may be quite slow on large tables. To speed up this process, you may keep track of the references in a hash that will provide much faster access. Something like this may work:

local cache = {}

local function findValue(key)
  if cache[key] == nil then
    local value
    -- do a linear search iterating through table elements searching for 'key'
    -- store the result if found
    cache[key] = value
  end
  return cache[key]
end

If the elements in the table change their values, you'll need to invalidate the cache when the values are updated or removed.

like image 191
Paul Kulchenko Avatar answered Nov 04 '22 07:11

Paul Kulchenko