1
我在lua中編寫腳本,我需要做的是每次設置變量時運行一段代碼。在lua中設置變量的運行代碼
的代碼,我是:
plane = {}
plane.status = "foo"
plane.status = "bar"
我想這個值被分配給一個變量在飛機每次
print "status=" + <value>
我怎麼會去這樣運行?我認爲它與__newindex有關。
我在lua中編寫腳本,我需要做的是每次設置變量時運行一段代碼。在lua中設置變量的運行代碼
的代碼,我是:
plane = {}
plane.status = "foo"
plane.status = "bar"
我想這個值被分配給一個變量在飛機每次
print "status=" + <value>
我怎麼會去這樣運行?我認爲它與__newindex有關。
是的,您爲plane
設置了代理表併爲其設置了__newindex
元方法。
function managed(t,f)
return setmetatable({},{__index=t, __newindex=f})
end
plane = managed({},print)
plane.status = "foo"
plane.status = "bar"
在實踐中,在__newindex
元方法,你會使用rawset
設置在原表中的值。
請注意'__newindex'僅在*鍵不存在於表格*時調用。如果您希望能夠存儲該值並仍然攔截呼叫,則必須將值存儲在另一個表中,而不是存儲在* managed *表中。 –
@MichalKottman,當然。我的意思是*託管*原*表。我編輯了我的答案。 – lhf