Module:Export cargo table

From Terraria Wiki
Jump to navigation Jump to search

No documentation subpage exists yet for this module. Create one now.


local trim = mw.text.trim
local nowiki = mw.text.nowiki
local cargo = mw.ext.cargo

-- cache
local currentFrame

-- helper function
local getArg = function(key)
	local value = currentFrame.args[key]
	if not value then
		return nil
	end
	value = trim(value)
	if value == '' then
		return nil
	else
		return value
	end
end

-- credit: http://richard.warburton.it
-- this version is with trim.
local function explode(div,str) 
	if (div=='') then return false end
	local pos,arr = 0,{}
	-- for each divider found
	for st,sp in function() return string.find(str,div,pos,true) end do
		arr[#arr + 1] = trim(string.sub(str,pos,st-1)) -- Attach chars left of current divider
		pos = sp + 1 -- Jump past current divider
	end
	arr[#arr + 1] = trim(string.sub(str,pos)) -- Attach chars right of last divider
	return arr
end


---------------------------

return {
	go = function(frame)
		-- input arguments
		currentFrame = frame
		local _table, _fields = getArg('_table'), getArg('_fields')
		local _limit, _delimiter = getArg('_limit'), getArg('_delimiter')
		
		-- convert comma-separated string to table
		local fieldsArray = explode(',', _fields)
		
		-- "infinite" limit
		if _limit == '-1' then
			_limit = 10^12 -- there shouldn't be a table with more than a trillion rows
		end
		
		-- array of lines that will be concatenated into the output string
		local outputLines = {}
		
		-- query the table and iterate over its rows
		local queryResult = cargo.query(_table, _fields, { limit = _limit })
		for _, row in ipairs(queryResult) do
			local fieldStrs = {}
			-- iterate over the fields, in the order they were input in the argument
			for fieldId = 1, #fieldsArray do
				local fieldName = fieldsArray[fieldId]
				local fieldValue = row[fieldName]
				if fieldValue then
					table.insert(fieldStrs, fieldName .. '=' .. nowiki(fieldValue))
				end
			end
			local thisline = '{{#cargo_store:_table=' .. _table .. '|' .. table.concat(fieldStrs, '|') .. '}}'
			table.insert(outputLines, thisline)
		end
		return table.concat(outputLines, _delimiter)
	end,

}