之後再用file:read()將它們讀出來,
不過,一般遊戲設定的資料通常都是以table方式來紀錄,
而file:write()或file:read() 卻是以string為input/output對象,
所以我們還另外需要json來幫忙將做table和string的轉換:
local json = require("json") function saveTable(myTable, filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local file = io.open(path, "w") if file then local sTable = json.encode(myTable)--encode the table to string file:write( sTable ) io.close( file ) return true else return false end end function loadTable(filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local contents = "" local myTable = {} local file = io.open( path, "r" ) if file then local sTable = file:read( "*a" )-- read the entire contents of the file myTable = json.decode(sTable)--decode the string back to table io.close( file ) file = nil return myTable end return nil end接下來,在程式中要如何使用呢?
gameSettingsFileName = "mygamesettings.json" currentSettingsVersion = 3 myGameSettings = loadTable("mygamesettings.json") if(myGameSettings == nil or myGameSettings.version == nil or myGameSettings.version ~= currentSettingsVersion) then -- the default settings myGameSettings = {} myGameSettings.version = currentSettingsVersion myGameSettings.level = 2 myGameSettings.speed = 5 saveTable(myGameSettings, gameSettingsFileName) end myGameSettings.level = myGameSettings.level+1 saveTable(myGameSettings, gameSettingsFileName)
myGameSettings.名稱
回覆刪除那個名稱是API還是可以自己定義的變數
那是自己定義的
回覆刪除