Hi!
After the <const> attribute was introduced in Lua I was wondering:
What mistakes the <const> attribute may protect us from?
I don't remember such a situation when <const> (if it existed) would help me detect a mistake in my code.
IMO, when <const> attribute is used as intended (to mark variables which never change their values after initialization), it just makes code harder to write, harder to read, and does not bring any benefits.
But it seems that in some scenarios local <const> variables might be useful.
This is due to Lua bytecode optimization that <const> is involved in.
Simple example:
local A <const> = "aaaaa"
local B <const> = "bbbbb"
print(A)
Lua optimizes this script by removing unused constant B.
And the string "bbbbb" is also removed from bytecode (debug info should be stripped).
My idea is to define a lot of constants to let the user select only a few constants he needs.
Due to optimization, unused constants will be removed, and the compiled chunk will be tiny.
keys_config.lua
local VK_LBUTTON <const> = 0x01 -- Left Mouse Button
local VK_RBUTTON <const> = 0x02 -- Right Mouse Button
local VK_BACK <const> = 0x08 -- Backspace
local VK_TAB <const> = 0x09 -- Tab
local VK_RETURN <const> = 0x0D -- Enter
local VK_SHIFT <const> = 0x10 -- Shift
local VK_CONTROL <const> = 0x11 -- Ctrl
local VK_MENU <const> = 0x12 -- Alt
local VK_ESCAPE <const> = 0x1B -- Esc
local VK_SPACE <const> = 0x20 -- Space
local VK_A <const> = 0x41 -- A key
local VK_B <const> = 0x42 -- B key
(there are more than 200 virtual-key codes in the full list)
-- nothing should be changed above this line
actions.jump.keys = {VK_W, VK_CONTROL}
actions.fire.keys = {VK_SPACE, VK_LBUTTON}
actions.use.keys = {VK_RETURN, VK_RBUTTON}
But this solution does not compile: the number of constants exceeds the quota for local variables (200).
A local <const> variable which holds a simple constant (number or string) does not occupy a VM register.
It would be good if such variables do not count in local variables quota.
This way we would be able to define thousands of constants.