Hi I have a game that I am completely rewriting all my code to it. Learned how to code with this game so its all together around 20k lines of confusing terrible code and should be around 5k of efficient and sleek code. My game has tiny rare glitches and bug outs and im sure its due to the inefficient code. I have some questions in general about modular building. Any help is highly appreciated.
- My game in general has 7 main screens (main menu, 3 level chooser screens and 3 actually playing the game screen) the 3 for these represent easy, medium and hard. As you can imagine the 3 level chooser screens are almost all the same code and the 3 playing the game screens also are almost all the same code.
Question is I want to have a modular file that contains all the shared code of the 3 level chooser screens and another one that has all the shared code for the 3 game playing screens. Building modular makes this code global. Should I only use the modular approach for things that are in every screen or is this a perfect place and the whole point of building modular?
-
I have started this approach for reading and writing json. reading and writing json happens in every screen so thought this was a great place to start. I am having some problems and am pretty sure its me not understanding something correct. If this looks to be correct then the error is basically that it does not see jsonFunct.writeGameValues in main menu.
-
If you know a good link that has a good breakdown of modular building please let me know. Its not the easiest thing to find info on as the approach is not liked by many people as it can leave huge room for error if not done correctly as its global. I want to try and understand this completely to strengthen my coding knowledge.
modJson.lua
local file local gameValuesPath = system.pathForFile( "gameFiles.json", system.DocumentsDirectory ) local json = require( "json" ) local jsonFunct = {} function jsonFunct.write(filePath, fileContents) file = io.open(filePath, "w") if file then file:write(json.encode(fileContents)) end io.close(file) end --write game values function jsonFunct.writeGameValues(fileValues) fileValues2=fileValues jsonFunct.write(gameValuesPath, fileValues2) end --function to read json function jsonFunct.read(filePath) file = io.open(filePath, "r") if file then contents = file:read( "\*a" ) io.close(file) return contents end end --read game values file function jsonFunct.readGameValues() local jsonResult=json.decode(jsonFunct.read(gameValuesPath)) return jsonResult end return modJson
mainMenu.lua
local json = require( "json" ) local modAll = require( "modJson" ) local gameValues = {0,3,7,8,0,5} jsonFunct.writeGameValues(gameValues) local readGameValues = jsonFunct.readGameValues() print (readGameValues[2])
. I have changed this and am still getting “Attempt to index global ‘jsonFunct’ (a nil value)” .