title: Lua: converting from float to int
body: <p>Even though Lua does not differentiate between floating point numbers and integers, there are some cases when you want to use integers. What is the best way to covert a number to an integer if you cannot do a C-like cast or without something like Python's <code>int</code>?</p>
  
  <p>For example when calculating an index for an array in </p>
  
  <blockquote>
    <p>idx = position / width</p>
  </blockquote>
  
  <p>how can you ensure <code>idx</code> is a valid array index? I have come up with a solution that uses <code>string.find</code>, but maybe there is a method that uses arithmetic that would obviously be much faster. My solution:</p>
  
  <pre><code>function toint(n)
      local s = tostring(n)
      local i, j = s:find('%.')
      if i then
          return tonumber(s:sub(1, i-1))
      else
          return n
      end
  end
  </code></pre>