简体   繁体   English

如何在Lua中将外部文件用作表格?

[英]How do I use external files as tables in Lua?

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. 我想使用外部文件来存储武器的数据,而不是在Lua文件本身中添加表。 I have tried using Lua files to store the data as a table. 我尝试使用Lua文件将数据存储为表格。

I have a file called sword.lua in the same folder as the program I want to access it's information. 我有一个名为sword.lua的文件,与我想要访问它的程序相同的文件夹。 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. 要从文件加载表,请使用require函数。 For example, save 例如,保存

return { 'sword', '10', '1', '100' }

as sword.lua . sword.lua Why do I just use return instead of assigning to a variable? 为什么我只使用return而不是赋值给变量? 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. 如果我将表分配给文件中的变量sword ,我会被锁定在该命名约定中,而且我会污染全局命名空间,从而更有可能发生名称冲突。

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, ie even if you require("sword") many times, you only pay the cost for loading once. 另一个优点是可以缓存对require调用,即使你多次require("sword") ,你只需支付一次加载的费用。 But keep in mind that because of caching you always get a handle to the same table, ie if you alter the table returned from require("sword") , these modifications will be shared by all instances. 但请记住,由于缓存,您总是得到同一个表的句柄,即如果您更改从require("sword")返回的表,则所有实例将共享这些修改。

Example on Wandbox Wandbox上的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM