lua-users home
lua-l archive

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


Oops, the cache does not work like this:

2011/6/11 Julien Desgats <julien.desgats@gmail.com>:
> Here is a minimal version (without any check, though) which convert
> camel case names into hyphen-separated strings. But the behavior can
> be unexpected if there is digits or special characters into keys.
>
> Type = setmetatable({}, {
>  __index = function(t, key)
>    local name = key:gsub("%u%l*", function(s) return s:upper().."-"
> end) .. "MAP"
>    t.key = name -- cache the name to allow fast further access
>    return name
    t[key] = name -- works better now !
>  end
> })
>
> print(Type.Arabia, Type.GoldRush)
>
> If you really need to constraint possible input values, you can put a
> "set" of available keys in metatable and check it :
>
> Type = setmetatable({}, {
>  keys = {
>    Arabia = true,
>    GoldRush = true,
>  },
>  __index = function(t, key)
>    if not getmetatable(t).keys[key] then return nil end -- if key is
> not allowed, return nil
>    local name = key:gsub("%u%l*", function(s) return s:upper().."-"
> end) .. "MAP"
>    t.key = name
>    return name
>  end
> })
>
> 2011/6/11 PROXiCiDE <saiyuk7@gmail.com>:
>> Hi is there a way to minimize the repeat typing of such.. -MAP at the end?
>> say...
>>
>>  Normal Version
>>      Type = {
>>         Arabia = "ARABIA-MAP",
>>         Archipelago = "ARCHIPELAGO-MAP",
>>         Baltic = "BALTIC-MAP",
>>         Coastal = "COASTAL-MAP",
>>         Continental = "CONTINENTAL-MAP",
>>         CraterLake = "CRATER-LAKE-MAP",
>>         Fortress = "FORTRESS-MAP",
>>         GoldRush = "GOLD-RUSH-MAP",
>>         Highland = "HIGHLAND-MAP",
>>         Islands = "ISLANDS-MAP",
>>         Mediterranean = "MEDITERRANEAN-MAP",
>>         Migration = "MIGRATION-MAP",
>>         Rivers = "RIVERS-MAP",
>>         TeamIslands = "TEAMISLANDS-MAP",
>>         Scenario = "SCENARIO-MAP"
>>      }
>>
>>  Minimal Version?? If possible
>>      Type = Map {
>>         Arabia,
>>         Archipelago,
>>         ....so on and so on
>>      }
>>
>>
>>
>