I want to make a program that chooses a random monster from a list, give the user a list of usable weapons, and allows them to choose which weapon to use. I want to use external files to store data for the weapons instead of adding the tables in the Lua file itself. I have tried using Lua files to store the data as a table.
I have a file called sword.lua in the same folder as the program I want to access it's information. It contains
sword = {'sword', '10', '1', '100'}
I am trying to access the information using
wep = io.open("sword.lua", "r")
print(wep:read("*a"))
print(wep[1])
The first print returns all of the text in the file which is
"sword = {'sword', '10', '1', '100'}"
and the second is supposed to return the first item in the table. Every time I do this, I get a nil value from the second print. The file is being read, as indicated by the first print listing the text, but how do I make it read the file as a table that I can use in my program.
To load a table from a file use the require
function. For example, save
return { 'sword', '10', '1', '100' }
as sword.lua
. Why do I just use return
instead of assigning to a variable? It's because that is much more flexible. If I assign the table to the variable sword
inside the file, I'm sort of locked into that naming convention and furthermore I pollute the global namespace, making name collisions more likely.
With the above solution I can also assign to a local variable, like so
local sword = require("sword")
print(table.concat(sword,", "))
Another advantage is that calls to require
are cached, i.e. even if you require("sword")
many times, you only pay the cost for loading once. But keep in mind that because of caching you always get a handle to the same table, i.e. if you alter the table returned from require("sword")
, these modifications will be shared by all instances.