Advertisement
xThomas

list.lua

Jul 5th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.25 KB | None | 0 0
  1. -- a simple implementation of a basic push/pop stack
  2. list_stack = {
  3.  
  4.     _items = {},
  5.  
  6.     push = function(self, item)
  7.         table.insert(self._items, item)
  8.     end,
  9.  
  10.     pop = function(self)
  11.         return table.remove(self._items)
  12.     end,
  13.  
  14.     -- the top item in the stack will tell us which kind of list we are in right now
  15.     get_top = function(self)
  16.         return self._items[#self._items]
  17.     end;    
  18.  
  19. }
  20.  
  21. -- push "unordered" unto the top of the stack
  22. function ul()
  23.     x = x + font.li:getWidth "\t"
  24.     list_stack:push{"unordered"}
  25. end
  26.  
  27. -- reverse the operations of ul() and
  28. -- pop the stack and raise an error if you're closing with the wrong kind of list
  29. function popul()
  30.     x = x - font.li:getWidth "\t"
  31.     local popped_mode = list_stack:pop()
  32.     assert(popped_mode[1] == "unordered", "Trying to close a <ol> with </ul>")
  33. end
  34.  
  35. -- push "ordered", 0, unto the top of the stack
  36. function ol()
  37.     x = x + font.li:getWidth "\t"
  38.     list_stack:push{"ordered",0}
  39. end
  40.  
  41. -- reverse the operations of ol() and
  42. -- pop the stack and raise an error if you're closing with the wrong kind of list
  43. function popol()
  44.     x = x - font.li:getWidth "\t"
  45.     local popped_mode = list_stack:pop()
  46.     assert(popped_mode[1] == "ordered", "Trying to close a <ul> with </ol>")
  47. end
  48.  
  49. function li(text)
  50.     local width, lines = font.li:getWrap(text, wrap or love.graphics.getWidth())
  51.     local height = font.li:getLineHeight() * font.p:getHeight()
  52.     love.graphics.setFont(font.li)
  53.  
  54.     -- notice how instead of just looking at a simple variable,
  55.     -- we're looking at the top of the stack. That way, once you close a list,
  56.     -- the previously opened one will take effect
  57.     -- I also added a check to make sure you're using <li> inside either <ul> or <ol>
  58.     local list_top = list_stack:get_top()
  59.  
  60.     if list_top[1] == "ordered" then
  61.         list_top[2] = list_top[2] + 1
  62.         love.graphics.print(list_top[2], x, y)
  63.     elseif list_top[1] == "unordered" then
  64.         love.graphics.print("•", x, y)
  65.     else
  66.         error("Trying to use <li> without matching <ul> or <ol>")
  67.     end
  68.  
  69.     local x = x + font.li:getWidth"\t"
  70.     for i = 1, #lines do
  71.         love.graphics.print(lines[i], x, y)
  72.         y = y + height
  73.     end
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement