PDA

View Full Version : Lua 101



bronxbomber92
August 8th, 2006, 15:19
These is kind of a "mini wiki" per say. Just basic commands, definitions, functions, ect...
Look for animation, shooting,jumping and simple AI to be added next!
THIS WILL BE UPDATED FREQUENTLY, AND FEEL FREE TO POST ANYTHING YOU WOULD LIKE ADDED, Thanks

Escape Sequences
-- These commands can be used when you are in certain situation dealing with strings. For those of you who are not familiar with strings, a string is "a sequence of characters". Now, back to escape sequences. Say you want to print
"I printed text within quotes" it wolud be impossible todo this without the escape sequence(s)
\" --double quote
\' --single quote since all text must be put in quotes for it to print. So an example of the code for this is
screen:print("\"in quotes\"")
The rest of the escape sequences are as follows
\a --bell
\b --back space
\f --form feed
\n --newline
\r --carriage return
\t --horizontal tab
\v --vertical tab
\\ --backslash
\" --double quote
\' --single quote
\[ --left square bracket
\] --right square bracket

Menu
ok Im going to show you three different ways to make a menu. But there are other ways ;)

1.)
-- initialize black and white colors
black = Color.new(0, 0, 0)
white = Color.new(255, 255, 255)

index = 1 -- initialize index value to "1" (top of menu)
xIcon = 0 -- x coordinate of Icon: in this example, it remains at 0
yIcon = 0 -- y coordinate of Icon: it moves up and down by 15 pixels

-- create the offscreen image (where the menu options will be printed - NOT the icon)
offscreen = Image.createEmpty(480, 272)
offscreen:clear(black)

-- checks index of menu to perform an action based on user's choice
-- insert the code you want your menu choices to perform HERE.
function menuCode ()
screen:clear(white)

if index == 1 then
screen:print(0, 0, "You have chosen 'Play'.", black)

else if index == 2 then
screen:print(0, 0, "You have chosen 'Options'.", black)

else if index == 3 then
screen:print(0, 0, "You have chosen 'Exit'.", black)
end
end
end

screen.flip()
end

-- takes table values of 'menu' and prints the menu to offscreen
function printMenu ()
for i = 0, table.getn(menu)-1 do
offscreen:print(10, i*15, menu[i+1], white)
end
end

-- Direction: 1 = up , 2 = down
function moveIcon (direction)
screen:clear(black) -- reset/clear the screen every time the icon moves
screen:blit(0, 0, offscreen, false)

-- if the direction of the menu is up, make sure that position is valid and move the icon
-- also changes the index value of the menu, and sets new Y coordinate for the icon
if direction == 1 and index > 1 and index <= table.getn(menu) then
index = index - 1
yIcon = yIcon - 15

-- if the direction of the menu is down, make sure the position is valid and move the icon
-- also changes the index value of the menu, and sets new Y coordinate for the icon
else if direction == 2 and index >= 1 and index < table.getn(menu) then
index = index + 1
yIcon = yIcon + 15
end
end

-- prints the Icon to the screen
screen:fillRect (xIcon, yIcon, 5, 5, white)
screen.waitVblankStart(4)
screen.flip()
end

-- declare your menu and initialize values
menu = {}
menu[1] = "Play"
menu[2] = "Options"
menu[3] = "Exit"

-- call function to print menu onto screen
printMenu()

screen:blit(0, 0, offscreen, false) -- print offscreen
screen:fillRect(xIcon, yIcon, 5, 5, white) -- place/initialize icon onto screen
screen.flip()

while true do
pad = Controls.read()

if pad:start() then
break
end

if pad:down() then
-- calls moveIcon function with direction = 2 (DOWN)
moveIcon(2)
end

if pad:up() then
-- calls moveIcon function with direction = 1 (UP)
moveIcon(1)
end

if pad:cross() then
-- calls the actual code you want your menu choices to perform
menuCode()
end

screen.waitVblankStart()
end

2.)
red = Color.new(255,0,0)
black = Color.new(0,0,0)
white = Color.new(255,255,255)

menustatus = 1

while true do
screen:clear(black)
pad = Controls.read()

if pad:up() then
menustatus = menustatus - 1
screen.waitVblankStart(4)
end

if pad:down() then
menustatus = menustatus + 1
screen.waitVblankStart(4)
end

color={white, white, white}

screen:print(50, 50, "Play", color[1])
screen:print(50,60,"Options", color[2])
screen:print(50,70,"Exit", color[3])

color[menustatus]=red

if menustatus == 1 then
if pad:cross() then
--insert game code here
end
end

if menustatus == 2 then
if pad:cross() then
--insert options here
end
end

if menustatus == 3 then
if pad:cross() then
break
end
end

if menustatus <= 0 then
menustatus = 3
end

if menustatus => 4 then
menustatus = 1
end

screen.flip()
screen.waitVblankStart()
end

3.)
function menuoption(xpos,ypos,txt, cursor,num_cursor_char,co l,selcol,selcondition)
screen:print(xpos,ypos,tx t,col)
if selcondition then
screen:print(xpos-(8*num_cursor_char),ypos, cursor .. txt,selcol)
end
end
I suggest most use the second one as its the most understandable and more efficient then the first one. But the third is more advance but more efficient.

Functions
Functions are first-class values in Lua. That means that functions can be kept (or stored) in variables, be used inside another functions, and returned as results.
The following functions are built in functions specific to the PSP Lua player

Graphics


Font Font.load(filename)

Loads a true type font.


Font Font.createMonoSpaced()

Creates an instance of the built-in mono-spaced font.


Font Font.createProportional()

Creates an instance of the built-in proportional font.


Font Font:setCharSize(number width, number height, number dpiX, number dpiY)

Changes the size of the current font to the specified point size height and width (if width is 0, it will be calculated proportional to the height for every character). dpiX and dpiY is the resolution of the display (see the Freetype documentation for details).


Font Font:setPixelSizes(number width, number height)

Changes the size of the current font to the specified pixel size height and width (if width is 0, it will be calculated proportional to the height for every character). (see the Freetype documentation for details).


width, height Font:getTextSize(string)

Returns the width and height, which will be used, if the specified text is drawn with this font and the current font size.


Image Image.createEmpty(width, height)

Creates an empty image, initially cleared. Max width and height is 512.


Image Image.load( filename )

Loads an image. Currently JPEG and PNG files are supported.


nil image:blit(x, y, Image source, [sourcex, sourcey, width, height], [alpha = true])

Paints the image, which is specified as “source” to the image on which this function is called on (or to the double buffered screen, when using the “screen:blit(...)” variable, which is a special image). “sourcex” and “sourcey” is the position in the source image, from where a rectangle of the size width/height is copied.


nil image:clear([color = transparent-black])

Sets all pixels of an image to the specified color.


nil image:fillRect(x, y, width, height, [color = transparent-black])

Draws a filled rectangle.


nil image:drawLine(x0, y0, x1, y1, [color = black])

Draws a line. TODO: Clipping needs to be enhanced.


Color image:pixel(x, y) --get

Gets the color of a pixel. See for example this code to get the color of an pixel and assert the value of all color components:

image = Image.createEmpty(1, 1)
color = image:pixel(0, 0)
colors = color:colors()
assert(colors.r == 0)
assert(colors.g == 0)
assert(colors.b == 0)
assert(colors.a == 0)


nil image:pixel(x, y, Color) --set

Sets the color of a pixel.


nil image:print(x, y, text, [color = black])

Prints some text with a predefined fixed width font with 8×8 pixels per character.


nil image:fontPrint(font, x, y, text, [color = black])

Prints some text with the specified true type font.


Number image:width()

Returns the width of an image.


Number image:height()

Returns the height of an image.


nil Image:save( filename )

Saves an image to memory stick. Currently JPEG and PNG files are supported.


global Image screen

The special double buffered screen object, which has all methods of an image and some more, see below.


nil screen.flip() -- note the small s; this is a function of the screen

Flips the offscreen and onscreen screen.


nil screen.waitVblankStart([count])

Waits until vertical retrace starts.


Color Color.new(r, g, b, [a=255])

Creates a new color object with the specified RGBA values.


table[r,g,b,a] color:colors()

Returns the RGBA values of a color object.


Bool (Color a == Color b)

Color objects are equal, if all RGBA components are equal.

3D GU mapping

Note: The 3D API might change in future.


Gu.start3d() saves the current GE state for the normal 2D operations. Call this function first and then draw your scene. You can use the following functions:

Gu.clearColor, Gu.clearDepth, Gu.clear, Gum.matrixMode, Gum.loadIdentity, Gum.perspective, Gum.translate, Gum.rotateXYZ, Gu.texImage, Gu.texFunc, Gu.texEnvColor, Gu.texFilter, Gu.texScale, Gu.texOffset, Gu.ambientColor, Gu.enable, Gu.disable, Gu.blendFunc, Gu.light, Gu.lightAtt, Gu.lightColor, Gu.lightMode, Gu.lightSpot and Gum.drawArray. See the PSPSDK for documenation about the parameters, for example the pspgu.h. If there is a ScePspFVector3, write 3 numbers instead one parameter (this will be changed in a later version). Whereever a color is expected, use a Color object. For textures use an Image object.

Gum.drawArray is something special: It has just 3 parameters: “prim”, “vtype” and a table. With “prim” you specify which primitive should be used, for example Gu.TRIANGLES. “vtype” specifies the vertex format and the transformation operation. For example “Gu.COLOR_8888|Gu.VERTEX_32BITF|Gu.TRANSFORM_3D” means, that your vertices has a color component and a 3 vertex coordinate components and is transformed before passed to the rasterizer. The table is then a list of vertex entries, where each vertex entry has the form (color, x, y, z). If you have specified GU_TEXTURE_32BITF, too, then one entry looks like this: (textureU, textureV, color, x, y, z). The order of the entries is defined in pspgu.h: textureU, textureV, color, normalX, normalY, normalZ, vertexX, vertexY, vertexZ. Indices, weights and multiple vertices per entry (which you’ll need for the morphing feature) currently are not supported.

After drawing anything, call Gu.end3d(), which flushs the display buffer and draws all pending 3D graphics and restores the 2D GE state. Don’t forget to call a screen:clear() before fullscreen 2D operations, because otherwise the z-buffer is not cleared and the blitting functions may not work correctly. If you need to blit 2D images in 3D mode, use textures and triangles.

See the 3D Cube example in the Applications folder of the distribution of Lua Player to see how to use the 3D functions and take a look at the GU example in the PSPSDK how to use all the other functions. Most of the time you can copy and paste the examples and just remove all those C fussinesses like “.0f”, semicolon, malloc etc. :-)

Controls


Controls Controls.read()


Bool controls:select()
Bool controls:start()
Bool controls:up()
Bool controls:right()
Bool controls:down()
Bool controls:left()
Bool controls:l()
Bool controls:r()
Bool controls:triangle()
Bool controls:circle()
Bool controls:cross()
Bool controls:square()
Bool controls:home()
Bool controls:hold()
Bool controls:note()


Number controls:analogX() -- ranges from -127 to 128.


Returns the current analog stick position in x direction.


Number controls:analogY() -- same


Returns the current analog stick position in y direction.


Bool (Controls a == Controls b) -- note! The analog stick is NOT considered when comparing because of analog fluctuations.


Compares two pad states.


Number controls:buttons() -- returns the bitmask like sceCtrlReadBufferPositive reads it


Constants for binary operations on buttons() result (for example “Controls.read():buttons() & Controls.startMask > 0” is the same as “Controls.read():start()”)


Number Controls.selectMask
Number Controls.startMask
Number Controls.upMask
Number Controls.rightMask
Number Controls.downMask
Number Controls.leftMask
Number Controls.ltriggerMask
Number Controls.rtriggerMask
Number Controls.triangleMask
Number Controls.circleMask
Number Controls.crossMask
Number Controls.squareMask
Number Controls.homeMask
Number Controls.holdMask
Number Controls.noteMask

Millisecond Timer


Timer Timer.new([startTime])

Creates a new Timer object, sets to 0 or startTime in milliseconds, if specified BUT don’t start ticking as yet.


Number Timer:start()

Starts to tick the timer (incrementing by one every millisecond), or resumes to tick after being stopped. Returns the current time() value. If the timer is running, it is the same as time().


Number Timer:time()

Returns in milliseconds since the timer started/resumed.


Number Timer:stop()

Stops the timer. Returns the current time(). Subsequent time() calls returns the value when stopped. If the timer is stopped, this call is the same as time().


Number Timer:reset([startTime])

Resets the timer to 0 by default or startTime in milliseconds and holds the timer. Returns the time before resetted to the new value.

System


String System.currentDirectory() -- get


Gets the current working directory.


String System.currentDirectory( path ) -- set, returns old path.


Sets the current working directory.


table System.listDirectory( [path] )

Lists the contents of the current working directory or the specified path. The result is a table of tables, where each table-entry has the string entry “name”, the number entry “size” and the boolean entry “directory”, which is set to true, when the current entry is a directory. See for example this code to print all files in the current working directory:


files = System.listDirectory()

for index, file in files do
print(file.name)
end


nil System.createDirectory(path)

Creates a new directory. The path is relative to the current directory, if not absolute.


nil System.removeDirectory(path)

Deletes a directory. The path is relative to the current directory, if not absolute.


nil System.removeFile(path)

Deletes a file. The path is relative to the current directory, if not absolute.


nil System.usbDiskModeActivate()

Activates the USB mode. Attention: When writing from USB to the memory stick, you must not write from within your Lua script to the memory stick, until you disable USB, otherwise the filesystem of your memory stick gets corrupted and you have to reformat your memmory stick.


nil System.usbDiskModeDeactivate()

Deactivates the USB mode.

Battery functions:


Bool System.powerIsPowerOnline()


Bool System.powerIsBatteryExist()


Bool System.powerIsBatteryCharging()


Number System.powerGetBatteryChargingStatus()


Bool System.powerIsLowBattery()


Number System.powerGetBatteryLifePercent()


Number System.powerGetBatteryLifeTime()


Number System.powerGetBatteryTemp()


Number System.powerGetBatteryVolt()


Number System.powerTick()

When called, it resets the internal power off counter, which prevents auto power off.


String System.md5sum(String)

Calculates the md5sum of a string. For example print(System.md5sum(io.input(”EBOOT.PBP”):read(”*a ”))) prints the same digest as “md5sum EBOOT.PBP” on Unix.

Serial input/output functions:


nil System.sioInit(baudrate)


Opens the SIO device and sets the baud rate. This needs some seconds to power up the UART.


System.sioWrite(string)

Writes the string to the SIO


string System.sioRead()

Reads all available data from the SIO. Returns an empty string, if no data was received.


System.sleep(number)

Pauses program execution for the specified time in milliseconds. It doesn’t affect any timer object.

IrDA functions:


nil System.irdaInit()

Opens the IrDA device. Call this to start the IrDA module.


System.irdaWrite(string)

Writes the string to the IrDA port.


string System.irdaRead()

Reads all available data from the IrDA port. Returns an empty string, if no data was received.


number System.getFreeMemory()

Gets the available free memory. You can use it like this:
print("about " .. System.getFreeMemory() / 1024 / 1024 .. " megabytes free memory available")

continued...

bronxbomber92
August 8th, 2006, 15:19
Sound and music


nil Music.playFile( string file, bool loop )

Plays a music in one of the following formats: UNI, IT, XM, S3M, MOD, MTM, STM, DSM, MED, FAR, ULT or 669.


nil Music.pause()

nil Music.resume()

nil Music.stop()

bool Music.playing()

Number Music.volume( [number {0-128}] )

nil SoundSystem.SFXVolume( number {0-128} )

nil SoundSystem.reverb( number {0-15} )

nil SoundSystem.panoramicSeparation( number {0-128} )

Sound Sound.load(filename, )

Voice sound:play()

nil voice:stop()

nil voice:resume(Sound) -- DISABLED due to bug.


nil voice:volume( number [0-25] )

nil voice:pan( number [0-255] )

nil voice:frequency( number [0-255] )

bool voice:playing()

WLAN


Wlan.init()

Must be called once at program start to initialize the WLAN module.


nil Wlan.term()

Unloads the WLAN module.


array Wlan.getConnectionConfigs()

Gets the available WiFi connection configurations.


Wlan.useConnectionConfig(number)

Selects the connection configuration. The number is the index in the array that is returned by Wlan.getConnectionConfigs (e.g. use 1 for the first configuration).


string Wlan.getIPAddress()

Gets the IP address of the PSP.


Socket Socket.connect(host, port)

Creates a new TCP/IP Socket object and starts the connection process to the specified host and port. All sockets are non-blocking.


bool Socket:isConnected()

Returns true, when the connection is established. Now recv and send can be called on this socket object.


Socket Socket:createServerSocket(port)

Creates a server socket, which listens on the specified port for incoming connections.


Socket Socket:accept()

Can be called for server sockets and returns a new incoming connection socket or nil, if no incoming connection is waiting.


string Socket:recv()

Reads and returns all available data from the socket or returns an empty string, if no data is available.


number Socket:send(string)

Sends a string. The result is the number of bytes which was sent (which can be less than the length of the string) or less than 0, if an error occured.


nil Socket:close()

Closes a socket.

[b]Collision

Well there are many different ways write collision, and many different situations specific to the game, So with this said, this section will never be complete, but updated as frequently as possible.

" It's a simple collision detection script for a 2D game from a birds eye view. It works by getting the coordinated of the four corners, and checks to see if any of the corners are within the other shape.



function hitTest(ob1x, ob1y, ob1width, ob1height, ob2x, ob2y, ob2width, ob2height)

--Title: Basic Collision Detection
--Author: CanadaRox

hit = false

if ((ob1x >= ob2x and ob1x <= (ob2x+ob2width)) and (ob1y >= ob2y and ob1y <= (ob2y+ob2height))) then
hit = true
end

if (((ob1x+ob1width) >= ob2x and (ob1x+ob1width) <= (ob2x+ob2width)) and (ob1y >= ob2y and ob1y <= (ob2y+ob2height))) then
hit = true
end

if ((ob1x >= ob2x and ob1x <= (ob2x+ob2width)) and ((ob1y+ob1height) >= ob2y and (ob1y+ob1height) <= (ob2y+ob2height))) then
hit = true
end

if (((ob1x+ob1width) >= ob2x and (ob1x+ob1width) <= (ob2x+ob2width)) and ((ob1y+ob1height) >= ob2y and (ob1y+ob1height) <= (ob2y+ob2height))) then
hit = true
end

return hit

end


Arguments:
ob1x = first object's x position
ob1y = first object's y position
ob1width = first object's width
ob1height = first object's height
ob2x = second object's x position
ob2y = second object's y position
ob2width = second object's width
ob2height = second objects height "
--quoted from CanadaRox

Greyscale Image Function
- created by FxN

This function takes a given picture and creates a black and white version of it.

--FxN '06 greyscale Image Function --
greyscale = function(tempimg)
temp2img = tempimg
for x = 0, (tempimg:width() -1) do
for y = 0, (tempimg:height() -1) do
origcolor = tempimg:pixel(x,y)
origcolors = origcolor:colors()
tempcolor = ((origcolors.r - 50) + (origcolors.g - 50) + (origcolors.b - 50) / 3)
newcolor = Color.new(tempcolor,tempcolor,tempcolor)
temp2img:pixel(x,y, newcolor)
end
end
return temp2img
end --greyscale
--FxN '06 greyscale Image Function --

myimg = Image.load("test.jpg")
screen:clear()
screen:blit(0,0, greyscale(myimg))
screen.flip()
while not Controls.read():start() do
screen.waitVblankStart(1)
end

Negative Image Effect Function
--created by FxN

This function takes a picture and creates a negative version.

--FxN '06 Negative Image Function --
invertcolors = function(tempimg)
temp2img = tempimg
for x = 0, (tempimg:width() -1) do
for y = 0, (tempimg:height() -1) do
origcolor = tempimg:pixel(x,y)
origcolors = origcolor:colors()
newcolor = Color.new(255 - origcolors.r, 255 - origcolors.g, 255 - origcolors.b)
temp2img:pixel(x,y, newcolor)
end
end
return temp2img
end
--FxN '06 Negative Image Function --

while running == true do
ctrls = Controls.read()
screen:clear()
screen:blit(0,0, invertcolors(myimg))
screen.flip()
screen.waitVblankStart(120)
if ctrls:start() == true then running = false end
end

Drawing a circle
--Created by FxN

This draws a circle and takes 5 arguements:
1.Target = What we are drawing on
2.X coordinate
3.Y coordinate
4.Radius of the circle
5.Color

The X and Y coordinates are for the middle point of the circle

function drawcircle(target, ux, uy, crad, ccolor)
degree = 0
while degree < (6.4) do
target:pixel((math.floor(crad * math.cos(degree)))+ux, (math.floor(crad * math.sin(degree))) +uy, ccolor)
degree = degree + 0.005
end
end --drawcircle
---circle function

red = Color.new(255,0,0)
screen:clear()
drawcircle(screen,100,100, 50, red)
screen.flip()
while not Controls.read():start() do
screen.waitVblankStart(1)
end

Fadepro Print Function
--created by FxN

ok so to call the function you need to have a font ready, i wrote and tested this using the built in proportional font but dont see why the truetype or monospaced fonts wouldnt work so give em a go and let me know. I changed it slightly from fontPrint so that the y value you give actually will be the top of the text.

So fadeproprint() takes 8 arguments:
1.Target (what to print to, usually screen)
2.X Coordinate
3.Y Coordinate
4.Font to use
5.String
6.First Color (will be on top or on the left side)
7.Second Color
8.Fade Axis (0 = Horizontal Fade, 1 = Vertical Fade)

--FxN '06 Fadepro Print Function
function fadeproprint(target, px, py, font, pstr, color1, color2, axis)
tracecolor = Color.new(1,0,0)
if axis == 1 then
tempcolor = color1
color1 = color2
color2 = tempcolor
end
if px == 0 then px = 1 end
if py == 0 then py = 1 end
colors1 = color1:colors()
colors2 = color2:colors()
colors = { 0 }
while table.getn(colors) ~= 256 do
table.insert(colors, tracecolor)
end
for counter = 1, 256 do
if colors1.r < colors2.r then colors1.r = colors1.r + 1 end
if colors1.r > colors2.r then colors1.r = colors1.r - 1 end
if colors1.g < colors2.g then colors1.g = colors1.g + 1 end
if colors1.g > colors2.g then colors1.g = colors1.g - 1 end
if colors1.b < colors2.b then colors1.b = colors1.b + 1 end
if colors1.b > colors2.b then colors1.b = colors1.b - 1 end
colors[counter] = Color.new(colors1.r, colors1.g, colors1.b)
colors[counter+1] = Color.new(colors1.r, colors1.g, colors1.b)
colors[counter+2] = Color.new(colors1.r, colors1.g, colors1.b)
colors[counter+3] = Color.new(colors1.r, colors1.g, colors1.b)
counter = counter + 4
end
txtsize = font:getTextSize(pstr)
tempy = py
py = py + txtsize.height
tempx = px
target:fontPrint(font, px, py, pstr, tracecolor)
if tempy <= 0 then tempy = 1 end
if tempx <= 0 then tempx = 1 end
if axis == 0 then
while tempx ~= (px + txtsize.width + 1) do
while tempy ~= (py) do
if target:pixel(tempx,tempy) == tracecolor then
target:pixel(tempx, tempy, colors[math.floor(256 / txtsize.width * (tempx - (px - 1)))])
end
tempy = tempy + 1
end
tempy = py - txtsize.height
tempx = tempx + 1
end
end
if axis == 1 then
while tempx ~= (px + txtsize.width + 1) do
while tempy ~= (py) do
if target:pixel(tempx,tempy) == tracecolor then
target:pixel(tempx, tempy, colors[math.floor(256 / txtsize.height * (py - (tempy)))])
end
tempy = tempy + 1
end
tempy = py - txtsize.height
tempx = tempx + 1
end
end
end --fadeproprint
--FxN '06 Fadepro Print Function

red = Color.new(255,0,0)
blue = Color.new(0,0,255)
propo = Font.createProportional()
propo:setPixelSizes(0,80)

while not Controls.read():start() do
screen:clear()
fadeproprint(screen, 78, 77, propo, "FadePro", red, blue, 0)
propo:setPixelSizes(0,40)
fadeproprint(screen, 194,147, propo, "Print", red, blue, 1)
propo:setPixelSizes(0,80)
screen.flip()
screen.waitVblankStart()
end

HSL to RGB & RGB to HSL function
-created by FxN


HSLtoRGB = function(hslcolor)
ch = hslcolor.h / 256
cs = hslcolor.s / 256
cl = hslcolor.l / 256

if cs == 0 then
cr = cl
cg = cl
cb = cl
else
if cl < 0.5 then temp2 = cl * (cl + cs)
else temp2 = (cl + cs) - (cl * cs)
end

temp1 = 2 * cl - temp2
tempr = ch + 1 / 3

if tempr > 1 then tempr = tempr - 1 end
tempg = ch
tempb = ch - 1 / 3
if tempb < 0 then tempb = tempb + 1 end

if tempr < 1 / 6 then cr = temp1 + (temp2 - temp1) * 6 * tempr
elseif tempr < 0.5 then cr = temp2
elseif tempr < 2 / 3 then cr = temp1 + (temp2 - temp1) * ((2 / 3) - tempr) * 6
else cr = temp1
end

if tempg < 1 / 6 then cg = temp1 + (temp2 - temp1) * 6 * tempg
elseif tempg < 0.5 then cg = temp2
elseif tempg < 2 / 3 then cg = temp1 + (temp2 - temp1) * ((2 / 3) - tempg) * 6
else cg = temp1
end

if tempb < 1 / 6 then cb = temp1 + (temp2 - temp1) * 6 * tempb
elseif tempb < 0.5 then cb = temp2
elseif tempb < 2 / 3 then cb = temp1 + (temp2 - temp1) * ((2 / 3) - tempb) * 6
else cb = temp1
end

end
rgbcolor = Color.new(math.floor(cr * 255), math.floor(cg * 255), math.floor(cb * 255))
return rgbcolor
end --HSLtoRGB
--FxN '06 HSLtoRGB

counter = 0
while not Controls.read():start() do
mycolor = { h = counter, s = 255, l = 128 }
screen:clear(HSLtoRGB(mycolor))
screen.flip()
screen.waitVblankStart(1)
counter = counter + 1
if counter == 256 then counter = 0 end
end


Ok so now why is this HSL to RGB so cool then?
well first thing you can do with it is the example shown above, you can use a simple counter to fade through the spectrum by changing the hue value. If you leave the hue value and just use a counter you can fade a color from black to the color and then to white by changing the lightness value or more like fading color to black, black to color, color to white, white to color...whater, or you can play around with the saturation.

I bet you can come up with bucketloads of cool effects you can do with playing around with counters and that function but to use that function with image manipulation you want to be able to convert RGB to HSL so you can read an image, read it pixel by pixel and change the hue, saturation or the lightness of the image...so i made RGB to HSL function:


--FxN '06 RGBtoHSL
RGBtoHSL = function(colorRGB)
colorsRGB = colorRGB:colors()
cr = colorsRGB.r / 256
cg = colorsRGB.g / 256
cb = colorsRGB.b / 256
mincolor = math.min(cr, cg, cb)
maxcolor = math.max(cr, cg, cb)
if mincolor == maxcolor then
ch = 0
cs = 0
cl = cr
else
cl = (mincolor + maxcolor) / 2
if cl < 0.5 then cs = (maxcolor - mincolor) / (maxcolor + mincolor)
else cs = (maxcolor - mincolor) / (2 - maxcolor - mincolor)
end

if cr == maxcolor then ch = (cg -cb) / (maxcolor - mincolor)
elseif cg == maxcolor then ch = 2 + (cb - cr) / (maxcolor - mincolor)
else ch = 4 + (cr - cg) / (maxcolor - mincolor)
end

ch = ch / 6
if ch < 0 then ch = ch + 1 end
end
hslcolor = { h = 0, s = 0, l = 0 }
hslcolor.h = math.floor(ch * 255)
hslcolor.s = math.floor(cs * 255)
hslcolor.l = math.floor(cl * 255)
return hslcolor
end --RGBtoHSL
--FxN '06 RGBtoHSL


Read more about HSL:
http://en.wikipedia.org/wiki/HSL_color_space

I know HSL isnt actually expressed in 0,0,0 - 255,255,255 but I find it alot easier to use like that so yes my functions use values between 0 and 255.

Concatenation

Concatenation is is a string operator espressed by ".." (two dots).
It can be used like so:
a = World

screen:print("Hello" .. a) -- prints this "Hello World"
It strings any two variables into a new string print the values as characters,

Table Constructors

Constructors are expressions that create and initialize tables (also they can initialize arrays). The most simplistic table constructor is the {}. What it does is create a empyty table ( e.g. emptyTable = {} ).
They can also be to essentially link a value to a number, to put it plainly. Let me show you an example:
months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" } Now if we were to say:
screen:print(month[1]) it would print January since the first value in the table months is January, and it continues down the months, so month[2] would be February, and so on and so forth.



~ PLEASE REMEMBER THIS WILL BE UPDATED CONSTANTLY, AND IT MAY LOOK MESSY BUT IT WILL ALL BE CLEANED FOR AN EASIER READ (e.g. wether its in code bracktes....) Thanks for being patience

I would like to give a special thanks to the whole psp and lua communtiy such as luaplayer.org members of QJ.net, ps2dev.org and many others who put time into documentation, wikis and tutorials. including shine, Charlie, Qj member who put forth effort into the menu example thread, all Lua developers, Fxn, canadaRox, and anyone else I missed.

bronxbomber92
August 8th, 2006, 15:20
reseved..

bronxbomber92
August 8th, 2006, 15:23
does anyone know why he code tags arent working properly? Should I use quote tags instead???

NoQuarter
August 8th, 2006, 16:48
Bookmarked! Thanx man I'm just starting out in lua and will visit this thread frequently I'm sure.

Apoklepz
August 8th, 2006, 16:48
Hey man. I got to say this will be very helpful and quite informative for a lot of people here...but some of the example code snippets are to big and jumbled up with words, I'm sure any noob wanting to learn Lua will glance at it and be like "forget about it..." You know what I mean? The other thing is you posted like five times...It is your own thread after all, but I think it would be wise to keep it down to one huge post...you don't want the mods breathing down your neck, here or anywhere...

Other than that...kudos!

yaustar
August 8th, 2006, 18:33
I would like to request a change in the title, this a LuaPlayer 101 not Lua (barring the table and string functions). The first few areas are from http://wiki.ps2dev.org/psp:lua_player:functions.

The remaining functions such as image malipuation is nice though.

drEDN4wt
August 8th, 2006, 18:36
Loads a gay type font.

whats wrong with a gay type font?

yaustar
August 8th, 2006, 18:39
Shouldn't that be true type font?

bronxbomber92
August 8th, 2006, 19:04
@apokletz, I have two posts for it because their is a character limit, so It cant load all in 1 post. Anf the code shouldnt be all smushed... its the coe tags... I'll try to fix that.

about the gay type font, I copied that part from wiki, so I think someone changed it in the wiki, so I will fix that.

yaustar
August 8th, 2006, 21:29
I would use quote tags, the code tags are pretty poor on this forum.

despoteuodia
August 11th, 2006, 01:25
i will need to referance this often, i am learning html at highschool, c++ at colledge as a dual enrolled student (all my classes + colledge) so lua will be too much to memorise. but this page will help endlessly. i personaly prefer the ide as opposed to the sdk, i dont like the way it operates. i suppose i will force my self to get over it. C++ is better, though more work.

yaustar
August 11th, 2006, 01:47
The Lua language itself is tiny and very BASIC/Pascal/C like. If you know C/C++, you can pick up the basics of Lua in less then a week (excluding all the metatable material). Don't get confused by people you regard LuaPlayer *as* Lua. 90% of the functions mentioned here are *purely* for LuaPlayer and not Lua.

Added note: An IDE is useless on it's own, you will need to setup a compiler or SDK with the IDE build any program (in regards to compile languages [eg C] )