View Single Post
11-07-15, 05:31 PM   #1
Benalish
A Flamescale Wyrmkin
 
Benalish's Avatar
Join Date: Dec 2012
Posts: 123
OnUpdate running function and memory saving

Disabling all add-ons and leaving active only the one created by me, I noticed large swings in memory consumption. This is probably because in OnUpdate event is launched this function, where tables are created all the time:

Lua Code:
  1. local function tokenize(C, strng)
  2.     local sChar = string.format('%c', C)
  3.     local sInput = strng or ""
  4.     local tReturn = {}
  5.     for sWord in string.gmatch(sInput, "[^"..sChar.."]+") do
  6.         table.insert(tReturn, tonumber(sWord) or sWord)
  7.     end
  8.     return tReturn
  9. end
  10.  
  11. local function gettok(sInput, iPosition, Separator, iRange)
  12.     local tTokens = tokenize( Separator, sInput )
  13.     if iPosition == 0 then return sInput end
  14.     local iStart, iStop = (iPosition > 0) and iPosition or (#tTokens + iPosition + 1)
  15.     if not iRange or iPosition == iRange then
  16.         return tTokens[iStart]
  17.     end
  18.     if iRange > 0 then
  19.         iStop = iRange
  20.     elseif iRange == 0 or (iStart + iRange) > #tTokens then
  21.         iStop = #tTokens
  22.     else
  23.         iStop = iStart + iRange + 1
  24.     end
  25.     if iStart == iStop then return tTokens[iStart] end
  26.     if iStart > iStop then
  27.         iStart, iStop = iStop, iStart
  28.     end
  29.     return table.concat(tTokens, Separator, iStart, iStop)
  30. end

Where

• sInput = string to manipulate
• iPosition = position of the token inside the string. If lesser than 0, it will be considered the position from the last token to the first. If equal to 0, returns the whole string.
• Separator = ASCII code of the token separator
• iRange = optional: if specified, returns the token from position to range. If equal to 0, return all tokens from position to the end of the string.

Some examples:

local text = "apple.banana.cherry.grape.orange"

gettok(text,1,46)
> apple

gettok(text,-2,46)
> grape

gettok(text,2,46,4)
> banana.cherry.grape

gettok(text,-1,46,-3)
> cherry.grape.orange

Now, can you give me some advice on how to eliminate these fluctuations in memory usage by bringing, as much as possible, some small example, and improve this code?

Thank you in advance
  Reply With Quote