abi>>forums

abi>>forums (http://www.anythingbutipod.com/forum/index.php)
-   Zen X-Fi2 Applications & Development (http://www.anythingbutipod.com/forum/forumdisplay.php?f=221)
-   -   Common Code Fragments (http://www.anythingbutipod.com/forum/showthread.php?t=52312)

bzdbbb 02-07-2010 08:29 AM

Common Code Fragments
 
Now that the SKD has been released and more people are getting into writing apps I thought it would be a good idea to have a thread devoted to useful reusable code functions that are not included in the standard Libraries.

I'll kick things off; :P

Returns true if the point x,y is within the region at rx,ry with the width w and height h, else returns false:
Code:

function withinRegion(x, y, rx, ry, w, h)

        if x >= rx and x <= (rx + w) and y >= ry and y <= (ry + h) then
                return true;
        else
                return false;
        end;

end;

Returns the distance in pixels between x,y and x1,y1
Code:

function pointDistance(x,y,x1,y1)
        local xdist;
        local ydist;
        local dist;
        xdist = math.abs(x-x1);
        ydist = math.abs(y-y1);
        dist = math.sqrt((xdist*xdist)+(ydist*ydist));
        return dist;
end;

If you've written any other useful functions or have a improvement to one already listed, please post :)

badazzmofo 02-08-2010 01:35 PM

does zenlua support class structure?

can i say

Quote:

class one
public function one( arg ) echo arg . 1; end;
private function two() return 2; end;
public function three( arg ) return two() + 1; end;
end;
so if you went

var test= new one("test");
you'd get test1

if you went
echo test.three()

you get a result of 3

but if you went
echo test.two()

you'd get nothing or an error

bzdbbb 02-08-2010 02:03 PM

Nope - Lua doesn't support classes. You can try and emulate them but its still just functions :P (I'm doing this in the scrolling shooter to allow instances)

badazzmofo 02-08-2010 02:11 PM

you mean like
function one()
public function one( arg ) echo arg . 1; end;
private function two() return 2; end;
public function three( arg ) return two() + 1; end;
end;

ive done that in javascript


how about private/public? does that work?

bzdbbb 02-08-2010 02:24 PM

You can't nest functions and there's no need for public/private stuff. There is just functions, that's it :P What you can do to emulate classes is to create a table which holds functions e.g. math.sqrt() is a function called sqrt in a table called math. This makes "math" like a class in other languages, but in Lua its just a table :P

ThievingSix 02-09-2010 08:20 PM

Classes can be emulated as Modules. Private/Public is done via the local command. Check out Apeopex for an example of that.

delirius 02-19-2010 10:38 AM

TILED map viewer
 
1 Attachment(s)
I have implemented simple viewer of tile maps. I just wanted to test if it can be done on X-fi 2, and how much of memory i will waste by map.

Currently there is not culling of not visible tiles, but it is still pretty fluent with map slightly bigger than screen.

Tiles are from TILED editor (free editor)

If someone finds it usefull, go ahead and use/change code.

cilmaviel 02-26-2010 07:03 PM

these may not be common, but they are probably helpful if you need them...

the distance between coordinates function can be shortened to

Code:

function dist(x1,y1,x2,y2)
    return math.sqrt((math.abs(x1-x2)*math.abs(x1-x2))+(math.abs(y1-y2)*math.abs(y1-y2)))
end

this function takes 3 coordinates and returns the area of any triangle, it uses the function above.

Code:

function triarea(x1,y1,x2,y2,x3,y3)
    local as = dist(x1,y1,x2,y2)
    local bs = dist(x2,y2,x3,y3)
    local cs = dist(x3,y3,x1,y1)
    local s = (as+bs+cs)/2
    return math.sqrt(s*(s-as)*(s-bs)*(s-cs))
end

this one is also dependent on the function above, it will return 1 if a point (x,y) is the the triangle, 0 if not.

Code:

function pointintriangle(ax,ay,bx,by,cx,cy)
    local defined_tri = (triarea(ax,ay,bx,by,cx,cy))
    local tri1 = (triarea(x,y,ax,ay,bx,by))
    local tri2 = (triarea(x,y,bx,by,cx,cy))
    local tri3 = (triarea(x,y,cx,cy,ax,ay))
    if math.floor(tri1+tri2+tri3) == math.floor(defined_tri) then
        return 1
    else
        return 0
    end
end

here is a simple collision system using point and box, i use it in monkey ball. ballsize is the diameter of the ball, bx and by are the coordinates of the center of the ball. bufferxavg and bufferyavg is the data from the accelerometer about the direction of tilt. if xmove or ymore are 0 (there is a check done elsewhere in the program before the ball is allowed to move). note, there may be a problem if a collision happens at a perfect 45 degree angle but i have not found any issues with it.

Code:

function obsticalarea(xmin,xmax,ymin,ymax)
    local ballright = ((bx ) + (ballsize / 2))
    local ballleft = ((bx ) - (ballsize / 2))
    local balltop = ((by ) - (ballsize / 2))
    local ballbottom = ((by ) + (ballsize / 2))
    local cright = xmax
    local cleft = xmin
    local ctop = ymin
    local cbottom = ymax
    cx = ((xmax-xmin)/2)+xmin
    cy = ((ymax-ymin)/2)+ymin
    xoffset = math.abs(bx-cx)
    yoffset = math.abs(by-cy)
    if bx < cx and xoffset > yoffset and ballright > cleft then
        if bufferxavg < 0 then
            xmove = 0
        else
            xmove = 1
        end
        ymove = 1
    elseif bx > cx and xoffset > yoffset and ballleft < cright then
        if bufferxavg > 0 then
            xmove = 0
        else
            xmove = 1
        end
        ymove = 1
    elseif by < cy and yoffset > xoffset and ballbottom > ctop then
        if bufferyavg > 0 then
            ymove = 0
        else
            ymove = 1
        end
        xmove = 1
    elseif by > cy and yoffset > xoffset and balltop < cbottom then
        if bufferyavg < 0 then
            ymove = 0
        else
            ymove = 1
        end
        xmove = 1
    else
        xmove = 1
        ymove = 1
    end
end

and here is a link to a psp lua development board. being psp most of the code is different but it may have some useful ideas.
http://forums.qj.net/psp-development...-snippets.html

Habhome 02-27-2010 02:01 AM

Quote:

Originally Posted by cilmaviel (Post 446258)
these may not be common, but they are probably helpful if you need them...

the distance between coordinates function can be shortened to

Code:

function dist(x1,y1,x2,y2)
    return math.sqrt((math.abs(x1-x2)*math.abs(x1-x2))+(math.abs(y1-y2)*math.abs(y1-y2)))
end

this function takes 3 coordinates and returns the area of any triangle, it uses the function above.

Code:

function triarea(x1,y1,x2,y2,x3,y3)
    local as = dist(x1,y1,x2,y2)
    local bs = dist(x2,y2,x3,y3)
    local cs = dist(x3,y3,x1,y1)
    local s = (as+bs+cs)/2
    return math.sqrt(s*(s-as)*(s-bs)*(s-cs))
end

this one is also dependent on the function above, it will return 1 if a point (x,y) is the the triangle, 0 if not.

Code:

function pointintriangle(ax,ay,bx,by,cx,cy)
    local defined_tri = (triarea(ax,ay,bx,by,cx,cy))
    local tri1 = (triarea(x,y,ax,ay,bx,by))
    local tri2 = (triarea(x,y,bx,by,cx,cy))
    local tri3 = (triarea(x,y,cx,cy,ax,ay))
    if math.floor(tri1+tri2+tri3) == math.floor(defined_tri) then
        return 1
    else
        return 0
    end
end


Nice! I have been starting to ponder over functions like these, now I don't have to come u with them myself anymore =P Thanks

Diddykong13 03-09-2010 10:35 AM

Animation
 
A function for realtime animation:
Code:

--LeftAnim
function moveleft()

Timer = Timer + 1;

    if Timer>= 9 or Timer<=0  then

    Timer = 0;

      end



        if Timer==2 then

        CurrentPlayerImg = manLeft1;

        end



        if Timer==4 then

        CurrentPlayerImg = manLeft2;

        end


               
    if Timer==6 then
 
        CurrentPlayerImg = manLeft3;

        end


        if Timer==8 then
 
        CurrentPlayerImg = manLeft2;

        end

end

-Place this function in a while loop for it to animate
-Put a CurrentPlayerImg:draw(playerx,playery); in the draw screen function to make it update

ThievingSix 03-13-2010 07:03 PM

Want to compile your code like Creatives Sudoku game? If so read on:
Quote:

Originally Posted by ThievingSix (Post 450860)
Haha, Ok I'll explain it.

First this is a script you run in the simulator or your player.

Code:

CodeOutput = io.open("CompiledCode.lua","wb");
Open the file you want your compiled application to output too.

Code:

CodeOutput:write(string.dump(assert(loadfile("MyCode.lua"))));
Lets break it down:
-loadfile("MyCode.lua")
>Basically this loads MyCode.lua from plaintext(the kind we type) and compiles it.
-assert(...)
>This makes sure that the file compiled error free.
-string.dump(...)
>This dumps the compiled code from our file into byte form so we can output it to file.
-CodeOutput:write(...)
>This writes the dumped data to the file.

Code:

io.close(CodeOutput);
Saves the compiled code we just wrote.


Now you have a file that contains compiled code("CompiledCode.lua") from a file that we just wrote and was not compiled("MyCode.lua"). You can now rename "CompildCode.lua" to "Main.lua" and it will run like normal, only no one can edit it. It can be mostly decompiled but its better than not.


cilmaviel 03-24-2010 06:50 PM

with the new firmware and everything, here is a script that creates a file "functions.lua" and lists all of the functions available.

Code:

local seen={}
file = io.open("functions.lua","w")
function dump(t,i)
    seen[t]=true
    local s={}
    local n=0
    for k in pairs(t) do
        n=n+1 s[n]=k
    end
    table.sort(s)
    for k,v in ipairs(s) do
        print(i,v)
        file:write(i, v, "\n")
        v=t[v]
        if type(v)=="table" and not seen[v] then
            dump(v,i.."\t")
        end
    end
end
dump(_G,"")


ThievingSix 03-24-2010 06:52 PM

My internet is too slow to update right now, any new functions found with that dump function?

cilmaviel 03-24-2010 07:13 PM

the accelerometer functions are the same as in the api. the only ones i have noticed are os.execute() and os.tmpname() i have not tested them yet though.

Tetrajak 03-24-2010 07:14 PM

New functions as listed by cilmaviel;

Quote:

os.tmpname ()
Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
On some systems (POSIX), this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it).
When possible, you may prefer to use io.tmpfile, which automatically removes the file when the program ends.
In the POSIX shell of the X-Fi2, the os.tmpfile function can be used to create new files on the device.

Quote:

os.execute ([command])
This function is equivalent to the C function system. It passes command to be executed by an operating system shell. It returns a status code, which is system-dependent. If command is absent, then it returns nonzero if a shell is available and zero otherwise.
os.execute can be used to run POSIX commandline functions, although what the returned codes mean, I am unsure.

Dump of output of cilmaviel's function, assess at your will;

Code:

_G
_VERSION
accelerometer
 close
 get_datatype
 get_samplerate
 getdata
 open
 set_datatype
 set_samplerate
assert
audio
 beep
 channel
 mute
 volume
button
 click
 event
 hold
 home
 power
 up
collectgarbage
color
 a
 b
 g
 new
 r
control
 isButton
 isSensor
 isTouch
 read
coroutine
 create
 resume
 running
 status
 wrap
 yield
debug
 debug
 getfenv
 gethook
 getinfo
 getlocal
 getmetatable
 getregistry
 getupvalue
 setfenv
 sethook
 setlocal
 setmetatable
 setupvalue
 traceback
dofile
dump
error
file
gcinfo
getfenv
getmetatable
image
 close
 create
 draw
 fill
 height
 load
 setbg
 setresource
 width
io
 close
 flush
 input
 lines
 open
 output
 popen
 read
 stderr
 stdin
 stdout
 tmpfile
 type
 write
ipairs
load
loadfile
loadstring
math
 abs
 acos
 asin
 atan
 atan2
 ceil
 cos
 cosh
 deg
 div
 exp
 floor
 fmod
 frexp
 huge
 ldexp
 log
 log10
 max
 min
 mod
 modf
 pi
 pow
 rad
 random
 randomseed
 sin
 sinh
 sqrt
 tan
 tanh
module
newproxy
next
os
 clock
 date
 difftime
 exit
 getenv
 ostime
 remove
 rename
 setlocale
 sleep
 time
 wait
package
 config
 cpath
 loaded
  _G
  accelerometer
  audio
  button
  color
  control
  coroutine
  debug
  image
  io
  math
  os
  package
  screen
  backlight
  clear
  drawline
  drawpixel
  drawrect
  fillrect
  height
  orientation
  update
  width
  string
  byte
  char
  dump
  find
  format
  gfind
  gmatch
  gsub
  len
  lower
  match
  rep
  reverse
  sub
  upper
  table
  concat
  foreach
  foreachi
  getn
  insert
  maxn
  remove
  setn
  sort
  text
  color
  draw
  size
  touch
  click
  down
  event
  hold
  move
  pos
  up
  wav
  close
  load
  play
  time
 loaders
  1
  2
  3
  4
 loadlib
 path
 preload
 seeall
pairs
pcall
print
rawequal
rawget
rawset
require
screen
select
setfenv
setmetatable
string
table
text
toint
tonumber
tostring
touch
type
unpack
wav
xpcall


ThievingSix 03-24-2010 07:18 PM

So accelerometer.set_senddatatype is now accelerometer.set_datatype. Same with the respective get().

I didn't notice os.execute() in the list?

Tetrajak 03-24-2010 07:23 PM

Quote:

Originally Posted by ThievingSix (Post 454919)
So accelerometer.set_senddatatype is now accelerometer.set_datatype. Same with the respective get().

I didn't notice os.execute() in the list?

Indeed, os.execute is not in the list. You'll have to ask cilmaviel about that one.

cilmaviel 03-24-2010 07:32 PM

Quote:

Originally Posted by ThievingSix (Post 454919)
So accelerometer.set_senddatatype is now accelerometer.set_datatype. Same with the respective get().

I didn't notice os.execute() in the list?

it's weird those 2 functions were in the list, but i ran it again and they were gone. when i turned the player off and back on after i installed the firmware it reset like others said, i may have ran this before it reset. execute may be limited to a small window of use.

Brett_val 03-25-2010 01:38 PM

I saw io.popen in the list. The wiki says that it is unsupported, but as it appears in the list now, does this mean that it now is supported?

Tetrajak 03-25-2010 03:27 PM

Quote:

Originally Posted by Brett_val (Post 455133)
I saw io.popen in the list. The wiki says that it is unsupported, but as it appears in the list now, does this mean that it now is supported?

I don't know, I guess it's up to whoever wants to try it out to report back on whether it was successful or not. It'd be very useful if it does work.


All times are GMT -5. The time now is 10:25 AM.