Corona SDK - Global Variable

最近在使用Corona SDK的StoryBoard功能,因為想要Share一些資訊,比如Facebook的token,或個人資料等等,查了一下Global Variables

在Corona裡,我們常用的宣告方法如下

local myvariable = 10

如果你想要宣告為Global,你可以把local拿掉,或者你可以使用_G.myvariable

myvariable = 10
_G.myvariable = 10

你也可以這樣測試

_G.myVariable = 20
print( myVariable )
-- console 會顯示20

如果想知道Global裡有哪些資訊,你可以把Table列舉出來

for k,v in pairs( _G ) do
   print( k .. " => ", v )
end

預設的結果

_G => table: 0x10d510f90
_VERSION => Lua 5.1
_credits_init => function: 0x108647cf0
_network_pathForFile => function: 0x101394180
al => table: 0x10868cc50
assert => function: 0x10868f3a0
audio => table: 0x108635da0
collectgarbage => function: 0x10138e7f0
coronabaselib => table: 0x10863b5f0
coroutine => table: 0x1086903b0
debug => table: 0x10136f730
display => table: 0x1013eb150
dofile => function: 0x10865e510
easing => table: 0x10138b600
error => function: 0x10865e540
gcinfo => function: 0x10865e570
getfenv => function: 0x1086a7f50
getmetatable => function: 0x10134d250
graphics => table: 0x108675420
io => table: 0x1013ef390
ipairs => function: 0x1013d2aa0
load => function: 0x10868fc90
loadfile => function: 0x10868fc30
loadstring => function: 0x1086b2ab0
lpeg => table: 0x10862c4d0
math => table: 0x10864a840
media => table: 0x1013d1a20
metatable => table: 0x10868caf0
module => function: 0x1013e0fd0
native => table: 0x1086559b0
network => table: 0x101393b40
newproxy => function: 0x108617180
next => function: 0x1013ec010
os => table: 0x10131c900
package => table: 0x10863fc10
pairs => function: 0x1013d9870
pcall => function: 0x1013ec040
print => function: 0x10863b660
rawequal => function: 0x1013c79a0
rawget => function: 0x1013c7a00
rawset => function: 0x1013e7ab0
require => function: 0x10138fbc0
select => function: 0x1013e7ae0
setfenv => function: 0x1013e7b10
setmetatable => function: 0x10134a3f0
string => table: 0x101311df0
system => table: 0x1013b2e60
table => table: 0x1013ad550
timer => table: 0x10138a550
tonumber => function: 0x10134a450
tostring => function: 0x1086067f0
transition => table: 0x10138e000
type => function: 0x10130ffb0
unpack => function: 0x10130ffe0
xpcall => function: 0x101310010

但就跟Javascript一樣,使用Global variable來存東西是很危險的
你可能會覆蓋到API裡的Global variable,或者大家如果都用Global variable是有可能彼此被覆蓋的而造成程式錯誤

像如下

_G.audio = true  --play audio if true, don't play if false
_G.type = "Gold"
_G.timer = timer.performWithDelay( 1000, doSomething )

你的audio,timer就失效了

所以訣竅就是

Don't use globals!

我們可以使用module的方式來實現variable的共享

mydata.lua

--my global space
local M = {}
return M

require module在不同的view

local myData = require( "mydata" )
myData.myVariable = 10

你會發現不同view的修改myData的資料是會相通的。

有人會想要在宣告function之前就用該function,所以才想用global variable,我們的建議是你應該先宣告該變數,之後再assign該變數即可

local doSomething  --forward declaration

local function makeSomethingHappen()
   local fred = 10
   doSomething( fred )
end

doSomething = function( param )
   print( param )
end

延伸閱讀

Goodbye Globals!

comments powered by Disqus