Log In  

Here is a simple function to convert a number to its hexadecimal string representation:

function num2hex(number)
    local base = 16
    local result = {}
    local resultstr = ""

    local digits = "0123456789abcdef"
    local quotient = flr(number / base)
    local remainder = number % base

    add(result, sub(digits, remainder + 1, remainder + 1))

  while (quotient > 0) do
    local old = quotient
    quotient /= base
    quotient = flr(quotient)
    remainder = old % base

         add(result, sub(digits, remainder + 1, remainder + 1))

  for i = #result, 1, -1 do
    resultstr = resultstr..result[i]

  return resultstr


    print(num2hex(255)) -- ff
    print(num2hex(10)) -- a
    print(num2hex(1050)) -- 41a
P#50079 2018-03-07 22:44 ( Edited 2018-03-08 19:41)

:: Felice

The built-in tostr() function can do hex if you pass a second arg of 'true':

> i=255
> print(tostr(i))
> print(tostr(i,true))

If you want something that isn't the full 32-bit value, you can strip off the '0x' and the leading/trailing '0's pretty easily using sub(). This is the function I use:

function hex(v) 
  local s,l,r=tostr(v,true),3,11
  while sub(s,l,l)=="0" do l+=1 end
  while sub(s,r,r)=="0" do r-=1 end
  return sub(s,min(l,6),flr(v)==v and 6 or max(r,8))

> print(hex(123))
> print(hex(15.5))
> print(hex(3/7))
P#50094 2018-03-08 07:24 ( Edited 2018-03-08 12:44)

Thanks Felice.

Really nice. I didnt know that (my lua knowledge is pretty weak)...

Guess I will remove some tokens...

P#50096 2018-03-08 08:22 ( Edited 2018-03-08 13:22)
:: Felice

It's less about Lua and more about knowing PICO-8's tiny API. It's based on the Lua API, but only some very basic parts of it. It's simplified in some ways, and a few things are a little different.

I find it's helpful to re-read the manual now and then. When I started, I would skim/skip parts of the manual. I either didn't use the functions at the time, or I didn't really understand why they were useful. After you've written for PICO-8 for a while, you start seeing what you need, and what's useful. When you re-read the manual, you find yourself saying, "AH! So that's what that is for!"

People like to say "RTFM!" I think they need to say "RTFMA!" too. :)

P#50106 2018-03-08 14:41 ( Edited 2018-03-08 19:43)

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2020-07-05 20:53 | 0.010s | 4194k | Q:18