My game has characters that have initial values: stats, names, descriptions, etc. For the most part it looks like I can save the character data in collections: unique graphics per character, for example. For stats, I decided on creating properties on a shared script which I could modify on a per-character basis as needed, since the properties are exposed for easy edit in the editor when clicking on the script in the collection.
But this doesn’t work for string values, like character names, descriptions, etc., as properties only allow the hashes, making it useless for strings intended for reading. And I obviously can’t go into the script to specify these values, because that would specify the values for all characters. I don’t see any other components that look like they would allow storage for string values. Is there any recommended way to create human-readable string values that can be either attached to characters or looked up according to some index provided by the character?
Yup, you want a lua module:
A module is generally just a table like any other. You can store any value in it with any key. So you can make a look-up table keyed by your hashed character name or whatever.
1 Like
So would that be a one-time script to be required by my character manager, that would have data for all the characters in it; or would it be possible to have a module of the same name in each character’s folder that a reference in a shared script could access the appropriate module for each character?
Lua modules work similarly to NodeJS modules if you’ve used those before, where you can separate your helper functions, static code, and configs into files and then reference the files easily to obtain their contents and access their information.
In your use case, you would probably be looking at creating a main/stats.lua
and within that file add a table and populate it with stats, possibly with something like this:
local M = {}
M.knight = {"coolness": 100, "damage": 7}
M.bard = {"coolness": 5000, "damage": 1}
return M
3 Likes
You could do it either way, that’s just personal preference.
Example 1: One module with all stats:
click to show
-- character-data module
local M = {}
M[hash("skeleton")] = {
speed = 200,
damage = 1,
health = 4,
}
M[hash("goblin")] = {
speed = 350,
damage = 1,
health = 2,
}
return M
-- character script
go.property("name", hash("skeleton"))
local charData = require "main.character-data"
function init(self)
self.data = charData[self.name]
end
Example 2: One module for each character’s stats:
click to show
-- main.characters.skeleton.lua
local M = {
speed = 200,
damage = 1,
health = 4,
}
return M
-- character script
go.property("name", hash("skeleton"))
local charDataByName = {
[hash("skeleton")] = require("main.characters.skeleton"),
[hash("goblin")] = require("main.characters.goblin"),
}
function init(self)
self.data = charDataByName[self.name]
end
4 Likes