Hmm, would the table be created just once when the function is compiled?
As Erendir pointed out, the function call "or -1" is obsolete because of the Constant capture {i.e. " + Cc('w')"} , and you can actually just have a table called instead of a function.
-- copied from http://www.gammon.com.au/forum/?id=8947
local BLACK = 1
local RED = 2
local GREEN = 3
local YELLOW = 4
local BLUE = 5
local MAGENTA = 6
local CYAN = 7
local WHITE = 8
-- colour styles (eg. @r is normal red, @R is bold red)
-- @- is shown as ~
-- @@ is shown as @
-- This table uses the colours as defined in the MUSHclient ANSI tab, however the
-- defaults are shown on the right if you prefer to use those.
local colour_conversion = {
k = GetNormalColour (BLACK) , -- 0x000000
r = GetNormalColour (RED) , -- 0x000080
g = GetNormalColour (GREEN) , -- 0x008000
y = GetNormalColour (YELLOW) , -- 0x008080
b = GetNormalColour (BLUE) , -- 0x800000
m = GetNormalColour (MAGENTA) , -- 0x800080
c = GetNormalColour (CYAN) , -- 0x808000
w = GetNormalColour (WHITE) , -- 0xC0C0C0
K = GetBoldColour (BLACK) , -- 0x808080
R = GetBoldColour (RED) , -- 0x0000FF
G = GetBoldColour (GREEN) , -- 0x00FF00
Y = GetBoldColour (YELLOW) , -- 0x00FFFF
B = GetBoldColour (BLUE) , -- 0xFF0000
M = GetBoldColour (MAGENTA) , -- 0xFF00FF
C = GetBoldColour (CYAN) , -- 0xFFFF00
W = GetBoldColour (WHITE) , -- 0xFFFFFF
-- add custom colours here
} -- end conversion table
-----------
-- our code: :)
local P, C, Ct, Cs, Cg, S, Cc = lpeg.P, lpeg.C, lpeg.Ct, lpeg.Cs, lpeg.Cg, lpeg.S, lpeg.Cc
local tmpcolorkeys = {}
for k,v in pairs(colour_conversion) do tmpcolorkeys[#tmpcolorkeys+1] = k end
local Colors = P"@" * C(S( table.concat(tmpcolorkeys, "") ))
tmpcolorkeys = nil -- Clean up on aisle tempvar!
local NotAt = P(1) - P"@"
local NotAColor = P(1) - Colors
local text = Cg(Cs( (NotAt + P"@-"/"~" + P"@@"/"@" + NotAColor )^1 ),"text")
local color = Cg( (Colors + Cc('w')) / colour_conversion ,"textcolour")
local res = Ct( Ct( color * text)^1)
split_colors = function (s)
return res:match(s)
end -- split
The above uses a table instead of a function.
It also loops through the table once, grabbing the keys instead of hard-coding them. The "-- Add custom colours here" comment accurately instructs all you'd need to do to add more colors.
The other thing to note is an optimization in the grammar for text. It would still work if you had just the "swap ~" or "swap @" or "anything that's not a color flag", but the LPEG engine's optimized to grab "not this single char". (In PCRE terms: [^@]+ is faster than .*?@?) Also, since this will be the case in most instances, why make it go through 2 failed test ops first? It's good form for LPEG coding. (I saw this in the LPEG webcast that Roberto I. did) |