I read on the wiki that memory is assigned to variables so that they can be referenced later in the script. Local variables are garbage collected. so they don't cause a memory leak, but what about dictionaries? Let's say I have a giant dictionary to define the stats of tools and various texts. Would putting all of that information in a table be inefficient?
newDictionary = { tools = { gold = {0, 0, 0}, silver = {0, 0, 0}, bronze = {0, 0, 0} }, text = { welcomeShop = "Welcome to the shop!", goodbyeShop = "Come back later!", purchaseShop = "Thank you for buying!" } }
(just an example, of course; imagine something much larger) If so, what's the more efficient way of making a dictionary?
My main concern is putting texts in the dictionary the player will only see once, such as in the storyline or in a quest
Most memory management is taken care of for you, especially when you're talking about values like strings, numbers, Vector3s, etc. Some tips to avoid memory leaks:
Your concern is with strings that the player will only see once. No matter where you store them (whether in the middle of an if statement, like if myVar == "pretend this is a very long string" then
, or a dictionary like you proposed), the string has to be kept in memory -- but, aside from reading it from a file, this is a fact of all computer programs.
You should consider the memory and performance cost of creating a table to be very small. The overhead of having "welcomeShop = "Welcome to the shop!"
in a table rather than hardcoding it is also very small.
Otherwise, your dictionary creation method is fine (in terms of syntax). If you wanted you could put a comma at the end of every item (even though putting it after the last item is optional in Lua) - doing so means that you can change the order of the items or add new items without having to remember to add/delete commas.
However, there is no value in putting all your variables/values inside a single dictionary. The tools
and text
dictionaries are good, but if your scripts are all just going to say things like newDictionary.text.welcomeShop
, you could skip the newDictionary
creation (declaring tools/text dictionaries separately) and just have text.welcomeShop
in your code - saves you typing and also is slightly faster (though dictionary lookups are very cheap, so don't worry about dictionary usage in general). (If you want maximum efficiency, also declare your variables local
-- due to how Lua works, this makes accessing them faster - if you intend to have more than 100 local variables (can't remember if it's 150 or 200), you might hit the limit, but you shouldn't need that many).
If the player will only see it once then there really isn't a need for a dictionary. Dictionaries are mostly to make it easier to draw back on something and reuse it. However, there is nothing wrong with making one if you want to.