android
  #1  
Old 02-07-2010, 09:29 AM
bzdbbb's Avatar
bzdbbb bzdbbb is offline
X-Fi2 Development Moderator
 
Join Date: Dec 2009
Location: Gloucestershire, UK
Posts: 94
Page 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
Reply With Quote

Advertisement [Remove Advertisement]

  #2  
Old 02-08-2010, 02:35 PM
badazzmofo badazzmofo is offline
Junior Member
 
Join Date: Dec 2009
Posts: 75
Default

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

Last edited by badazzmofo; 02-08-2010 at 02:52 PM.
Reply With Quote

  #3  
Old 02-08-2010, 03:03 PM
bzdbbb's Avatar
bzdbbb bzdbbb is offline
X-Fi2 Development Moderator
 
Join Date: Dec 2009
Location: Gloucestershire, UK
Posts: 94
Default

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)
Reply With Quote

  #4  
Old 02-08-2010, 03:11 PM
badazzmofo badazzmofo is offline
Junior Member
 
Join Date: Dec 2009
Posts: 75
Default

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?
Reply With Quote

  #5  
Old 02-08-2010, 03:24 PM
bzdbbb's Avatar
bzdbbb bzdbbb is offline
X-Fi2 Development Moderator
 
Join Date: Dec 2009
Location: Gloucestershire, UK
Posts: 94
Default

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
Reply With Quote

  #6  
Old 02-09-2010, 09:20 PM
ThievingSix ThievingSix is offline
Member
 
Join Date: Aug 2008
Posts: 218
Default

Classes can be emulated as Modules. Private/Public is done via the local command. Check out Apeopex for an example of that.
__________________
Only ONE more functions in the Wiki need addressing!
Zen X-Fi2 LUA Wiki
Want to protect your applications? Click Here!
Tower Defense Thread
Zen Lock - Protect Your Zen!
Reply With Quote

  #7  
Old 02-19-2010, 11:38 AM
delirius delirius is offline
Member
 
Join Date: Feb 2010
Posts: 131
Default TILED map viewer

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.
Attached Files
File Type: zip tiles.zip (40.1 KB, 30 views)
Reply With Quote

  #8  
Old 02-26-2010, 08:03 PM
cilmaviel cilmaviel is offline
Junior Member
 
Join Date: Jan 2010
Posts: 61
Default

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
Reply With Quote

  #9  
Old 02-27-2010, 03:01 AM
Habhome's Avatar
Habhome Habhome is offline
Moderator
 
Join Date: Jan 2010
Location: Sweden
Posts: 1,081
Default

Quote:
Originally Posted by cilmaviel View Post
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
__________________
"If you are good enough at English to apologize, then there is no need to." - A good friend of mine
Discovered something about the X-Fi2 you think others may not know? Post it here so others can learn about it!
Have a question about X-Fi2 apps? Consult the FAQ before creating a thread about it.
Like my work? Tell your friends. Don't like it? Tell me so I can improve. ^.^
Reply With Quote

  #10  
Old 03-09-2010, 11:35 AM
Diddykong13's Avatar
Diddykong13 Diddykong13 is offline
Junior Member
 
Join Date: Jan 2010
Location: England
Posts: 43
Default 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
__________________
Current Languages:
-English
-ActionScript 2.0
-Lua (almost)

Last edited by Diddykong13; 03-10-2010 at 11:17 AM. Reason: Error
Reply With Quote

  #11  
Old 03-13-2010, 08:03 PM
ThievingSix ThievingSix is offline
Member
 
Join Date: Aug 2008
Posts: 218
Default

Want to compile your code like Creatives Sudoku game? If so read on:
Quote:
Originally Posted by ThievingSix View Post
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.
__________________
Only ONE more functions in the Wiki need addressing!
Zen X-Fi2 LUA Wiki
Want to protect your applications? Click Here!
Tower Defense Thread
Zen Lock - Protect Your Zen!
Reply With Quote

  #12  
Old 03-24-2010, 07:50 PM
cilmaviel cilmaviel is offline
Junior Member
 
Join Date: Jan 2010
Posts: 61
Default

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,"")
Reply With Quote

  #13  
Old 03-24-2010, 07:52 PM
ThievingSix ThievingSix is offline
Member
 
Join Date: Aug 2008
Posts: 218
Default

My internet is too slow to update right now, any new functions found with that dump function?
__________________
Only ONE more functions in the Wiki need addressing!
Zen X-Fi2 LUA Wiki
Want to protect your applications? Click Here!
Tower Defense Thread
Zen Lock - Protect Your Zen!
Reply With Quote

  #14  
Old 03-24-2010, 08:13 PM
cilmaviel cilmaviel is offline
Junior Member
 
Join Date: Jan 2010
Posts: 61
Default

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.
Reply With Quote

  #15  
Old 03-24-2010, 08:14 PM
Tetrajak Tetrajak is offline
Member
 
Join Date: Feb 2010
Location: Oceania
Posts: 124
Default

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

Last edited by Tetrajak; 03-24-2010 at 08:21 PM.
Reply With Quote

  #16  
Old 03-24-2010, 08:18 PM
ThievingSix ThievingSix is offline
Member
 
Join Date: Aug 2008
Posts: 218
Default

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

I didn't notice os.execute() in the list?
__________________
Only ONE more functions in the Wiki need addressing!
Zen X-Fi2 LUA Wiki
Want to protect your applications? Click Here!
Tower Defense Thread
Zen Lock - Protect Your Zen!
Reply With Quote

  #17  
Old 03-24-2010, 08:23 PM
Tetrajak Tetrajak is offline
Member
 
Join Date: Feb 2010
Location: Oceania
Posts: 124
Default

Quote:
Originally Posted by ThievingSix View Post
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.
Reply With Quote

  #18  
Old 03-24-2010, 08:32 PM
cilmaviel cilmaviel is offline
Junior Member
 
Join Date: Jan 2010
Posts: 61
Default

Quote:
Originally Posted by ThievingSix View Post
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.
Reply With Quote

  #19  
Old 03-25-2010, 02:38 PM
Brett_val's Avatar
Brett_val Brett_val is offline
Senior Member
 
Join Date: Jan 2010
Location: The Netherlands
Posts: 636
Default

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?
Reply With Quote

  #20  
Old 03-25-2010, 04:27 PM
Tetrajak Tetrajak is offline
Member
 
Join Date: Feb 2010
Location: Oceania
Posts: 124
Default

Quote:
Originally Posted by Brett_val View Post
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.
Reply With Quote

Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump



All times are GMT -5. The time now is 04:51 AM.