Can Lua support case-insensitive methods?

I use Lua as the data description language for my C ++ application. I have a bunch of C ++ classes related to Lua using SLB 2.0. I have methods like "SetPos" or "SetName". I am specifying a position or name (for example) using a table with values ​​indicated as "pos" or "name". I want to be able to take the key, add a β€œset” and call the method if it exists (it may not be). Is it possible? If so, any suggestions?

I know that I can make my related methods more stringent, but I would prefer to keep them the same as the methods to which they are attached (this may be my flaw, though). I might try to create a method name based on my naming standards, but case insensitivity is less error prone.

I feel there must be a tricky piece of Lua that could solve this with metatables, but I myself could not handle it.

Any suggestions?

Thanks!

+4
source share
1 answer

Case insensitivity is not what Lua handles. All table scans and local access variables are eventually compared with a case-sensitive string.

The best solution would be to simply recognize that you are dealing with a case-sensitive system, like C ++, and dealing with it.

However, if you really want it, you can do it. The easiest way is to put all possible name permutations in your function table. So your function table will have the following:

["setname"] = theFunction, ["Setname"] = theFunction, ["sEtname"] = theFunction, ["SEtname"] = theFunction, ... 

You can, of course, automate this with a function that takes every name in the table and replicates its data based on case permutations.

A more complex, but easier to use mechanism will be the use of the __index and __newindex , as well as the empty table trick.

 function CreateCaseInsensitiveTable() local metatbl = {} function metatbl.__index(table, key) if(type(key) == "string") then key = key:lower() end return rawget(table, key) end function metatbl.__newindex(table, key, value) if(type(key) == "string") then key = key:lower() end rawset(table, key, value) end local ret = {} setmetatable(ret, metatbl) return ret end 

Instead of creating a table with {}, you create a table with this function call. Otherwise, the table should work fine (although obviously access to the member will be slightly slower).

+6
source

Source: https://habr.com/ru/post/1394263/


All Articles