lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



> On 7 Jun 2018, at 08:47, Domingo Alvarez Duarte <mingodad@gmail.com> wrote:
> 
> Hello !
> 
> I'm the author of https://github.com/mingodad/SquiLu a scripting language that reuses several things from Lua and seeing several discussion towards Lua 5.4 release I thought that would be nice to add some kind of "compiler checked strings constants".
> 
> What does I mean by "compiler checked strings constants" ?
> 
> One common mistake/error in scripting languages is the use of literal strings as key for hash tables and the compiler can't do anything to help us prevent spell errors, sometimes at runtime it'll be catched but not always, and it's a hard to find error.
> 
> Ruby has an ID type ":somename", in SquiLu I implemented "const :somename;" as a shortcut for 'const somename = "somename";' but still the compiler can not check it all the time, I was thinking to use some prefix for names that I want the compiler to check, could be something like "if($somename == somevariable)" like perl/php but only for compiled checked string constants.
> 
> I want to find an elegant syntax way to express this, does someone have any idea or example for it ?
> 
> Why not add something like this to Lua 5.4 ?
> 
> Cheers !
> 
> example:
> 
> const :passwrod;
> 
> ...
> 
> if(db_field.password == query_string_table[$password]) return true;
> 
> 
> 

Though it’s not compile time, I usually do something like this to catch them at run/test time

local const_mt = {
  __index = function(self, field)
    error("'" .. tostring(field) .. "' is not a valid constant", 2)
  end,
}

local function make_const(...)
  local res = {}
  for _, key in ipairs({...}) do
    res[key] = key
  end
  return setmetatable(res, const_mt)
end

local const = make_const("ONE", "TWO", "THREE")

print(const.ONE)    --> "ONE"
print(const.FOUR)   --> error


Thijs