我正在尝试将指定目录中的每个文件“导入”到表中,但是当我查看输出时,它只显示一个导入的文件。
使用“import”我的意思是require(dir.."/"..name)
这将返回一个值,该值将放在位于“name”的$ table中,所以这看起来像$ table [name]
我已经制作了以下代码,但它对我不起作用..我希望有人可以告诉我我做错了什么..
(以下代码已经过简化,但确实包含了与此功能相关的所有文件,结构和代码,我也插入了print()和printTable()以便进行调试)
我在Debian Jessie机器上工作
文件结构
~/x/main.lua
~/x/folder/file1.lua
~/x/folder/file2.lua
~/x/folder/file3.lua
~/x/folder/file4.lua
~/x/folder/file5.lua
./ main.lua (printTable script)
local printTable = require "printTable"
-- scan dir and add the file contents (name ,function(if .lua), filepath from script) to a table
function appendDir(functiontable,dir)
for filename in io.popen('dir "'..dir..'" -1'):lines() do
print(filename)
local path = dir.."/"..filename
local name = filename:sub(1,filename:len()-4)
print(name)
local tempValue = false
if filename:sub(filename:len()-3,filename:len()) == ".lua" then tempValue = require(dir.."/"..name) end
functiontable[name]={["value"]=tempValue,["path"]=path}
printTable(functiontable)
end
print("---")
printTable(functiontable)
end
local table1 = {}
appendDir(table1,"./folder")
print("")
print("table1:")
printTable(table1)
for key,value in pairs(table1) do
value.value()
end
./ folder / file * .lua 所有文件都以相同的方式构建,只有函数返回不同的字符串。
function func()
return "$string"
end
return func
以下字符串用于不同的文件,并插入 $ string 位置
~/x/folder/file1.lua $string=string of file 1
~/x/folder/file2.lua $string=string of file 2
~/x/folder/file3.lua $string=string of file 3
~/x/folder/file4.lua $string=string of file 4
~/x/folder/file5.lua $string=string of file 5
现在当我执行main.lua脚本时,我得到:
~/x $ lua -v
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
~/x $dir folder -1
file1.lua
file2.lua
file3.lua
file4.lua
file5.lua
~/x $ lua main.lua
file1.lua
file1
[file1][value] -> TYPE == function
[file1][path] -> VALUE == ./folder/file1.lua
file2.lua
file2
[file1][value] -> TYPE == function
[file1][path] -> VALUE == ./folder/file1.lua
file3.lua
file3
[file3][value] -> TYPE == function
[file3][path] -> VALUE == ./folder/file3.lua
file4.lua
file4
[file3][value] -> TYPE == function
[file3][path] -> VALUE == ./folder/file3.lua
file5.lua
file5
[file4][value] -> TYPE == function
[file4][path] -> VALUE == ./folder/file4.lua
---
[file4][value] -> TYPE == function
[file4][path] -> VALUE == ./folder/file4.lua
table1:
[file4][value] -> TYPE == function
[file4][path] -> VALUE == ./folder/file4.lua
答案 0 :(得分:0)
正如@EgorSkriptunoff在原帖的注释部分指出的那样,printTable函数中的一个错误是函数返回到for循环而不是内部函数。这已经解决并致力于github!
感谢您的帮助!