Associative array/Merging: Difference between revisions

added Lua solution
(added Lua solution)
Line 28:
|}
 
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
 
{| class="wikitable"
Line 43:
|}
 
 
=={{header|Lua}}==
<lang Lua>base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}
 
--[[ clone the base data ]]--
result = {}
for key,val in pairs(base) do
result[key] = val
end
 
--[[ copy in the update data ]]--
for key,val in pairs(update) do
result[key] = val
end
 
--[[ print the result ]]--
for key,val in pairs(result) do
print(string.format("%s: %s", key, val))
end</lang>
 
{{output}}
<pre>price: 15.25
color: red
year: 1974
name: Rocket Skates</pre>
 
=={{header|MiniScript}}==
222

edits