【发布时间】:2017-06-18 17:27:37
【问题描述】:
我是 Lua 的新手,我只是尝试做一些在其他语言中常见且简单的事情,但在 Lua 中的工作方式不同,因为函数的参数是通过引用传递的(我假设)。似乎也通过引用来向表中添加内容。伪代码:
objImage --stores details about each image like name, iso, aperture etc.
tblMetadata --table that has all the image names and associated data.
tblImages --table to hold the image objects (objImage)
for each line in tblMetadata
objImage.name = blahblah
objImage.iso = blahblah
etc...
table.insert(tblImages, objImage)
objImage = nil
end
在我使用过的大多数语言中,objImage = nil(或等效语言)会重置对象以允许将新图像添加到表中。但在 Lua 中,它将刚刚添加到表中的对象设置为 nil。以这样的迭代方式将一系列“对象”添加到表中的技术是什么?我尝试使用第二个 objImage (objImage2) 并将 objImage 分配给它,然后再将它 (objImage2) 添加到表中,但这只是将指针/引用分配给原始 objImage。
编辑:我的伪代码没有完全反映我想要做什么,所以我在下面添加了实际代码:
function extractExif(tblOutput)
local tblImages = {}
local blnFlag = false
local intCount = 0
local Image = {} --pseudo object to hold metadata for each image
for k,v in pairs(tblOutput) do --iterate through each value in the table
if string.find(v, "^=.+") then
--test if new image other than the first one
if blnFlag == true then
--add Image to tblImages and then clear Image object
table.insert(tblImages, Image)
Image = nil
blnFlag = false
end
i, j = string.find(v, "/") -- **** MAC ONLY. Back slash for Windows *****
Image.filePath = string.sub(v, i) --returns the file path
--Image.name = string.match(v, "([^/]+)$") --return the file name
blnFlag = true
elseif string.find(v, "ISO") ~= nil then
Image.iso = string.match(v, "%a+:(.+)") --get text (i.e value) to right of colon
elseif string.find(v, "Film") ~= nil then
Image.filmSim = string.match(v, "%a+:(.+)")
elseif string.find(v, "Setting") ~= nil then
Image.drMode = string.match(v, "%a+:(.+)")
elseif (string.find(v, "Auto") ~= nil) or (string.find(v, "Development") ~= nil) then -- corresponds to "Auto Dynamic Range" and "Development Dynamic Range" in fuji exif
Image.dr = string.match(v, "%a+:(.+)")
else
end
end
end
我当然可以通过使用嵌套表等而不是平面 tblOutput 元数据列表来更好地编程,我可能会在某个时候这样做。
【问题讨论】:
-
这段代码正确吗?
objTable变量是什么?你能贴一些真实的代码吗? -
对不起,应该是 objImage。我已经更正了。