'How do i copy an array from a lua file

I Want to copy an array from a text file and make another array equal it so

local mapData = {
    grass = {
        cam = "hud",
        x = 171,
        image = "valley/grass",
        y = 168,
        animated = true
    }
} 

This is an array that is in Data.lua

i want to copy this array and make it equal another array

local savedMapData = {}
savedMapData = io.open('Data.lua', 'r')

Thank you.



Solution 1:[1]

It depends on Lua Version what you can do further.
But i like questions about file operations.
Because filehandlers in Lua are Objects with methods.
The datatype is userdata.
That means it has methods that can directly be used on itself.
Like the methods for the datatype string.
Therefore its easy going to do lazy things like...

-- Example open > reading > loading > converting > defining
-- In one Line - That is possible with methods on datatype
-- Lua 5.4
local savedMapData = load('return {' .. io.open('Data.lua'):read('a'):gsub('^.*%{', ''):gsub('%}.*$', '') .. '}')()

for k, v in pairs(savedMapData) do print(k, '=>', v) end

Output should be...

cam =>  hud
animated    =>  true
image   =>  valley/grass
y   =>  168
x   =>  171

If you need it in the grass table then do...

local savedMapData = load('return {grass = {' .. io.open('Data.lua'):read('a'):gsub('^.*%{', ''):gsub('%}.*$', '') .. '}}')()

The Chain of above methods do...

  1. io.open('Data.lua') - Creates Filehandler (userdata) in read only mode
  2. (userdata):read('a') - Reading whole File into one (string)
  3. (string):gsub('^.*%{', '') - Replace from begining to first { with nothing
  4. (string):gsub('%}.*$', '') - Replace from End to first } with nothing

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1