如何从另一个lua文件加载数据? [英] How do I load data from another lua file?
问题描述
我有一个主要的lua文件app.lua,在该应用程序中有一个加载数据"按钮.注意:LUA 5.1不是5.2
I have a main lua file app.lua , and in that app I have a button to "load data" in. NOTE: LUA 5.1 not 5.2
数据文件是一个 lua 文件,里面也有表格.
The data file is a lua file as well with tables in it.
data1 = {
{a,b,c},
{1,2,3}
}
data2 = {
{d,e,f}
}
目标是在我选择加载文件时使这些表可用于应用程序.
The goal was to make those tables available to the app anytime I choose to load the file.
我在lua网站上尝试了该示例
I tried the example from the lua site
function dofile (filename)
local f = assert(loadfile(filename))
return f()
end
但是f()只是打印大量字符串.例如,我似乎无法访问 f.data1[1].
but f() is just printing a massive string. I can't seem to access f.data1[1] for example.
推荐答案
您正在加载的文件不是数据表.那是一段代码,可执行的匿名函数.您在 return f()
语句中运行该代码.
The file you're loading is not a data table. That's a piece of code, anonymous function that is executable. You run that code in return f()
statement.
但是请查看该代码的作用-它不返回任何内容.而是分配两个全局变量,即 data1
和 data2
.例如,您可以将它们作为 data1 [1]
来访问.
But see what that code does - it doesn't return anything. Instead it assigns two global variables, data1
and data2
. You can access those as data1[1]
for example.
您可以返回
正在加载的文件中的数据,这样就不会污染全局环境,并且可能看起来像您想象的那样:
You could return
the data in the file being loaded, that way it wouldn't pollute the global environment, and probably will look like you imagined it to be:
return {
data1 = { {a,b,c}, {1,2,3} },
data2 = { d,e,f}
}
在其他文件中:
local f = assert(loadfile(filename))
my_data = f()
print(my_data.data1[1][1])
这篇关于如何从另一个lua文件加载数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!