kts.table_merge – merge two Lua tables
require("classic")
result = kts.table_merge(table1, table2)
This creates a new table which contains all keys from both table1
and table2
, together with the corresponding values.
If the same key exists in both table1
and table2
, then the value from table2
is preferred.
A new table, consisting of the merged keys and their corresponding values, is returned.
If the inputs are not valid tables (or table-like objects) then errors will result.
Unlike all other kts
functions, kts.table_merge
is not actually a built-in part of the kts
table. Instead, this function is added to the kts
table the first time the classic
module is loaded. In other words, at least one module has to import classic
before kts.table_merge
becomes available.
This could be seen as a bug, because it is inconsistent with how the other kts
functions work. However, it is not normally an issue, because almost all Knights modules will (directly or indirectly) import classic
before doing anything else, and therefore, in practice, kts.table_merge
will always be available. (The only time this would become an issue is if someone wanted to completely replace the classic
module with a new implementation, for some reason.)
Consider the following code:
table1 = {a=1, b=2, c=3} table2 = {c=99, d=98, e=97} table3 = kts.table_merge(table1, table2)
After this code runs, table3
will be equal to {a=1, b=2, c=99, d=98, e=97}
.
The kts.table_merge
function is often used when we want to define a "base" version of some table, and then make several "variations" of it by adding new keys. An example of this can be seen in tiles.lua, where a door_base
table is defined, and then wood_door
and iron_door
tables are derived from it using table_merge
calls.