Jump to content

Recommended Posts

I'm trying to create a custom crock pot object. Due to issues with containers, I can't just use the cooking.lua code and functions, and so I copied them and tried my best to use them. Problem is, when I call a function I defined in modmain.lua, my component file can't use it.

So, how do I create a function that can be used in multiple files? Base game does this through the require command, but I can't use it in modmain, and creating a separate file and loading it in did not work (game returned nil when trying to call a function in all cases)

require works fine in modmain, you probably just loaded the wrong path.

require uses your modmain.lua's "current working directory"/scripts as the basepath.

So when you do require("prefabs/my_crockpot.lua"), it's actually loading from MY_MOD_FOLDER/scripts/prefabs/my_crockpot.lua

So, lets say your mod folder structure is 

MY_MOD_FOLDER (folder)
	modmain.lua
	modinfo.lua
	scripts (folder)
		thing_to_require.lua
		flame_broiled_turkey.lua

(assume flame_broiled_turkey has a really nice recipe in it) And you wanted functions from thing_to_require.lua, you would structure it like so

local module = {}

module.PrintMyFlameBroiledTurkeyRecipe = function()
	local data = require("flame_broiled_turkey")
	print("super secret recipe:", data)
end

return module

Then to load thing_to_require, your modmain would look like 

-- modmain.lua
-- blah blah very fancy mod stuff here
local my_module = require("thing_to_require")

-- print recipe
my_module.PrintMyFlameBroiledTurkeyRecipe()

IMPORTANT NOTE: Do NOT name your files the same way the game names theirs. That will cause many conflicts and issues that will take you an eternity to figure out. I recommend you prefix the filenames with something only your mod would use. So instead of cooking.lua, I suggest something like myfoodmod_cooking.lua

Edited by penguin0616
  • Like 2

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
  • Create New...