Search code examples
stringlualua-patterns

LUA: Generating Unique Mac from given Number Value


I am trying to generate a unique MAC id from given a number value. The length on the number is between 1 to 5 digit. I have formatted the MAC table to place each digit starting from first value of MAC.

local MacFormat ={[1] = "0A:BC:DE:FA:BC:DE",[2] = "00:BC:DE:FA:BC:DE",[3] = "00:0C:DE:FA:BC:DE",[4] = "00:00:DE:FA:BC:DE",[5] = "00:00:0E:FA:BC:DE"}

local idNumbers = {[1] = "1",[2]="12",[3]="123",[4]="1234",[5]="12345"}

for w in string.gfind(idNumbers[3], "(%d)") do
      print(w)
str = string.gsub(MacFormat[3],"0",tonumber(w))
    end
print(str)
---output 33:3C:DE:FA:BC:DE
--- Desired Output 12:3C:DE:FA:BC:DE

I have tried multiple Patterns with *, +, ., but none is working.


Solution

  • You can build the pattern and replacement dynamically:

    local MacFormat ={[1] = "0A:BC:DE:FA:BC:DE",[2] = "00:BC:DE:FA:BC:DE",[3] = "00:0C:DE:FA:BC:DE",[4] = "00:00:DE:FA:BC:DE",[5] = "00:00:0E:FA:BC:DE"}
    local idNumbers = {[1] = "1",[2]="12",[3]="123",[4]="1234",[5]="12345"}
    
    local p = "^" .. ("0"):rep(string.len(idNumbers[3])):gsub("(..)", "%1:")
    local repl = idNumbers[3]:gsub("(..)", "%1:")
    local str = MacFormat[3]:gsub(p, repl)
    
    print(str)
    -- => 12:3C:DE:FA:BC:DE
    

    See the online Lua demo.

    The pattern is "^" .. ("0"):rep(string.len(idNumbers[3])):gsub("(..)", "%1:"): ^ matches the start of string, then a string of zeros (of the same size a idNumbers, see ("0"):rep(string.len(idNumbers[3]))) follows with a : after each pair of zeros (:gsub("(..)", "%1:")).

    The replacement is the idNumbers item with a colon inserted after every second char with idNumbers[3]:gsub("(..)", "%1:").

    In this current case, the pattern will be ^00:0 and the replacement will be 12:3.

    See the full demo here.