0

I have std::map which contains list of values associated with a Key. Actual implementation contains many such Keys. Is there a similar way in Lua Table implementation which could hold multiple values for a specific key. If so how to write and read from that table.

I referred the How do I create a Lua Table in C++, and pass it to a Lua function? I have only access to set and get values which is on my C++ code which was written more generic and cannot create table in C++. (Third party C++ code).

All I have is I can get KeyType, Key, and Value using the

luaState = luaL_newstate(); lua_register(luaState, "getValue", get_value); lua_register(luaState, "setValue", set_value);.

The C++ code has something like

typedef std::set<const char *> TValueNames;
std::map<const char *, TValueNames> keyValueList;

By referring to Lua document I understood I can create a table with Key as index and assign value as its data. But I need to know how to assign multiple value(data) for one Key. https://www.lua.org/pil/2.5.html

The example lua script implementation is like,

local keyType = getValue("KeyType");
local Key = getValue("Key");
local Value = getValue("Value");
KeyValueTable = {}
KeyValueTable[Key] = Value;

I need to create something which could hold information like,

["Key1"] = {"Value1,Value2,Value3"};
["Key2"] = {"Value2,Value3,Value4,Value5"};
Community
  • 1
  • 1
kar
  • 495
  • 1
  • 8
  • 19
  • 1
    Do you need the table in LUA or C++. In C++ you can look at a `std::multimap`. – NathanOliver Jul 18 '16 at 17:23
  • I need table in Lua which could hold similar to std::map in C++ – kar Jul 18 '16 at 18:27
  • 1
    @kar: A `std::map` cannot hold multiple values per key. Only a `std::multimap` can do so. Your `keyValueList` is still only holding one value. It's just that this value happens to be a container that itself contains multiple things. But `map` itself is only holding a single object. – Nicol Bolas Jul 19 '16 at 02:21

1 Answers1

4

As you know, a key in a Lua table can only refer to one value, but you can easily make that value a table to hold multiple values. To more faithfully represent the set in the C++ structure, we can make the values into keys in the inner table.

local function setValue(self, key, value)
  self[key] = self[key] or {}
  self[key][value] = true
end

local function removeValue(self, key, value)
  if type(self[key]) == 'table' then
    self[key][value] = nil
  end
end

local function checkValue(self, key, value)
  if type(self[key]) == 'table' then
    return self[key][value]
  end
end
luther
  • 5,195
  • 1
  • 14
  • 24