Guest User

Color Text API

a guest
Feb 25th, 2014
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.80 KB | None | 0 0
  1. --Colored Text API by Civilwargeeky
  2. --Version 0.2
  3.  
  4. --[[Colors: white orange magenta lightBlue yellow lime pinkgray lightGray cyan purple blue brown green red black]]
  5.  
  6. local codes = {}
  7. for a, b in pairs(colors) do --This just makes a list of the colors to parse.
  8.   if type(b) == "number" then --I could just write them out, but where is the fun in that?
  9.     if a:sub(1,5) == "light" then
  10.       codes[a:sub(1,1)..string.lower(a:sub(6,6))] = b
  11.     elseif a == "blue" then
  12.       codes.db = b
  13.     else
  14.       codes[a:sub(1,2)] = b
  15.     end
  16.   end
  17. end
  18.  
  19. function encode(input) --Function to make colored strings
  20.   local currColor, toRet = codes.bl, {}
  21.   toRet.isColorText = true
  22.   for a, b in function() return input:find("%%%a%a") end do
  23.     local color = input:sub(a+1,b)..""
  24.     if codes[color] then
  25.       input =  input:sub(0,a-1)..input:sub(b+1,#input)
  26.       table.insert(toRet, {color = codes[color], start = a })
  27.     end
  28.   end
  29.   table.insert(toRet, 1, {color = codes.wh, start = 0})
  30.   toRet.text = input
  31.   local meta = {}
  32.   meta.__call = function(tab) return tab.text end
  33.   meta.__tostring = function(tab) return tab.text end
  34.   meta.__len = function(tab) return #tab.text end
  35.   setmetatable(toRet,meta)
  36.   return toRet
  37. end
  38.  
  39. local oldWrite = write
  40. write = function(input)
  41.   if input.isColorText and term.isColor() then
  42.     local currPos = 0
  43.     for i=1, #input do
  44.       startPos, endPos = input[i].start, (input[i+1] or {start = #input.text+1}).start-1
  45.       term.setTextColor(input[i].color)
  46.       oldWrite(input.text:sub(startPos,endPos))
  47.     end
  48.     term.setTextColor(codes.wh)
  49.     return true
  50.   else
  51.     return oldWrite(input)
  52.   end
  53. end
  54.  
  55. function writeCode(input)
  56.   return write(encode(input))
  57. end
  58.  
  59. local oldPrint = print
  60. print = function(input)
  61. return write(input), write("\n")
  62. end
Advertisement
Add Comment
Please, Sign In to add comment