Module:Sandbox/Matroc/ASCII code

Source: Wikipedia, the free encyclopedia.
-- Module:ASCII code   -- wjk -- User:Matroc
-- Minimal error checking - using Lua built in functions string.byte() and string.char()
-- could possibly change to mw.ustring.codepoint() and mw.ustring.char() for UTF-8
-- dealing with strings/numbers different for each of the above
-- using 32 or word "space" for return
-- essentially both functions for basic ASCII - 32 - 126 and not extended at this time
-- Just a basic test can be modified accordingly

-- Function to get number code for ASCII character is called asciicode
-- For invoke: {{#invoke:ASCII code|asciicode|{{(}}}}
-- Function to get character from number code
-- ie. {{#invoke|Code ASCII|codeascii|123}}

-- FUNCTION ASCIICODE

local p = {}

function p.asciicode(frame)
    local char = ""
    if frame.args[1] ~= nil and frame.args[1] ~= "" then       -- checking and create a default
          char = string.sub( frame.args[1], 1, 1 )             -- insure only 1 character or make default of space
       else
          char = " "
      end
      if char:byte() >= 32 and char:byte() <= 126 then         -- check if between 32 and 126 
           if char:byte() == 32 then                           -- if 32 for space then return 32
                  return 32
               else   
                  return char:byte()                           -- otherwise return the number
             end
           else
              return 32                                        -- input doesn't match up then return 32
        end
end


-- FUNCTION CODEASCII

function p.codeascii(frame)
      local num = "0"
      if frame.args[1] ~= nil and frame.args[1] ~= "" then
          num = frame.args[1] or "32"
       else
          num = "0"
       end
       num = tonumber(num)                         -- convert string to be a number
       if num == nil then num = 32 end             -- if tonumber failed make variable 32   
       if num >= 32 and num <= 126 then            -- if between 32 and 126 all is well
          if num == 32
              then
                 return "space"                    -- if 32 return word space
              else
                 return tostring(num):char()
            end
         else
            return "space"                         -- otherwise we will return the word space
       end
end

return p