Skip to content

How to implement ResolveRequire if custom function is used in game #3244

@vaderkos

Description

@vaderkos

In Civilization 5 there is special function include instead of require(Which is not available in most contexts) used for importing and running lua files.

How could I use ResolveRequire to automatically resolve specified files. (I know how to find file by import name).

For Example:

include('TechHelpInclude.lua') -- instead of require('path/to/TechHelpInclude')

-- Here I need to have lua definitions from that file already loaded, instead of manually finding and opening file.

Here is how you could emulate include function:

	local EmulateInclude = (function()
		local function GetAvailablePaths()
			-- We are not inside Civ5 Lua but somewhere else...
			local hasOs = os and type(os.getenv) == 'function'

			if not hasOs then
				error('Error in include emulation: Cannot determine OS')
			end

			local isWindows = os.getenv('OS'):lower():match('window')
			local windowsCmd = 'dir /s /b *.lua'
			local linuxCmd = "find . -type f -name '*.lua'"

			local stream = io.popen(isWindows and windowsCmd or linuxCmd)
			local files = {}

			if stream == nil then
				return files
			end

			for line in stream:lines() do
				table.insert(files, line)
			end

			return files
		end

		--- @param filename string
		local function GetCandidatePath(filename)
			for _, path in next, GetAvailablePaths(), nil do
				if string.sub(path, - #filename) == filename then
					return path
				end
			end

			return filename
		end

		--- @param filename string
		return function(filename)
			if not filename:match('%.lua$') then
				filename = filename .. '.lua'
			end

			if type(dofile) ~= 'function' then
				error('Error in include emulation: dofile is not a function')
			end

			local success, result = pcall(dofile, GetCandidatePath(filename))

			if not success then
				if result:find('^cannot open') then
					return {}
				end

				error('Error in include emulation: ' .. result, 3)
			end

			return { filename }
		end
	end)()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions