Lua.Table (Lua v1.0.0-rc.1)

View Source

In Lua, tables are the fundamental datastructure, which are used both as associative arrays (maps), and arrays (lists).

Lua.Table provides some utilities for working with Lua tables when passed back to Elixir.

Summary

Functions

Converts a Lua table into a list. Assumes that the table is correctly ordered.

Converts a Lua table into a map

Converts a Lua table into a string representing a Lua table literal

Converts a Lua table into more "native" feeling lists and maps, deeply traversing any sub-tables.

Functions

as_list(values, opts \\ [])

@spec as_list(
  [{term(), term()}],
  keyword()
) :: [term()]

Converts a Lua table into a list. Assumes that the table is correctly ordered.

iex> Lua.Table.as_list([{1, "a"}, {2, "b"}, {3, "c"}])
["a", "b", "c"]

To ensure the list is ordered, you can pass the :sort option

iex> Lua.Table.as_list([{2, "b"}, {1, "a"}, {3, "c"}])
["b", "a", "c"]

iex> Lua.Table.as_list([{2, "b"}, {1, "a"}, {3, "c"}], sort: true)
["a", "b", "c"]

Options

  • :sort - (default false) when true, sorts entries by their integer key before dropping keys, so the result is index-ordered regardless of the input order.

Returns

A list of the table's values in key order.

as_map(values)

@spec as_map([{term(), term()}]) :: map()

Converts a Lua table into a map

iex> Lua.Table.as_map([{"a", 1}, {"b", 2}])
%{"a" => 1, "b" => 2}

as_string(table, opts \\ [])

@spec as_string(
  list() | map(),
  keyword()
) :: String.t()

Converts a Lua table into a string representing a Lua table literal

iex> Lua.Table.as_string([{"a", 1}, {"b", 2}])
"{a = 1, b = 2}"

Lists that "look" like Lua tables are treated as lists

iex> Lua.Table.as_string([{1, "foo"}, {2, "bar"}])
~S[{"foo", "bar"}]

Lists are treated as lists

iex> Lua.Table.as_string(["a", "b", "c"])
~S[{"a", "b", "c"}]

Regular maps are always treated as tables

iex> Lua.Table.as_string(%{1 => "foo", "bar" => "baz"})
~S<{[1] = "foo", bar = "baz"}>

Options

  • :formatter - A 2-arity function used to format values before serialization. The key and value are passed as arguments. If there is no key, it will default to nil.

Returns

A string containing the Lua table literal.

deep_cast(value)

@spec deep_cast([{term(), term()}]) :: list() | map()

Converts a Lua table into more "native" feeling lists and maps, deeply traversing any sub-tables.

It uses the heuristic that maps with integer keys starting as 1 will be auto-cast into lists

iex> Lua.Table.deep_cast([{"a", 1}, {"b", [{1, 3}, {2, 4}]}])
%{"a" => 1, "b" => [3, 4]}

Returns

A list when the table looks like a 1-indexed array, otherwise a map. Nested tables are cast recursively.