Omnimaga

Calculator Community => TI Calculators => Lua => Topic started by: pianoman on June 21, 2011, 09:05:12 pm

Title: Lua Q&A
Post by: pianoman on June 21, 2011, 09:05:12 pm
Hi everyone! I couldn't find a good place to post various questions, so I thought I'd start this.

First of all, how do you use the timer and make it do something? All I can do is start it. :w00t:

Thank you!
Title: Re: Lua Q&A
Post by: Ashbad on June 21, 2011, 09:30:41 pm
You can start the timer with Timer.start(period), which sets a period of time in seconds for the timer to start.  You can then set up an on.timer() event that is activated every timer tick. You can stop it with timer.stop().
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 22, 2011, 03:07:01 am
Here is a little example:

Code: (Lua) [Select]

number = 0

function on.paint(gc)

    --If number is still zero (we just started the application), start the timer (set to tick every 1 seconds)
    if number==0 then
        timer.start(1)
    end

    --Draw the number on the screen
    gc:drawString(tonumber(number),10, 10, "top")
end


--This get's now called every 1 seconds until you stop the timer
function on.timer()
    --Add one to number
    number = number + 1

    --Force the screen to be redrawn
    platform.window:invalidate()

    --If number is 10, stop the timer
    if number==10 then
        timer.stop()
    end
end

Title: Re: Lua Q&A
Post by: pianoman on June 22, 2011, 11:00:08 pm
Oh, got it. Thanks!
Title: Re: Lua Q&A
Post by: pianoman on June 29, 2011, 04:06:41 pm
Another one:
are you able to change values of an array in the program?
Thanks!
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 29, 2011, 04:16:52 pm
Well, technically speaking its tables in Lua :)

Lets say you have this table:
Code: (Lua) [Select]
a={1,2,3,4,5}Then you can change the third item with this command:
Code: (Lua) [Select]
a[3] = 1337Your table will then look like this:
Code: (Lua) [Select]
{1,2,1337,4,5}
Title: Re: Lua Q&A
Post by: pianoman on June 29, 2011, 04:18:01 pm
Omigod that just made a game a million times easier.
Thanks!
Title: Re: Lua Q&A
Post by: pianoman on June 30, 2011, 10:20:21 am
How about this one: are you able to check if two tables are equal to each other?
for example:
Code: [Select]
a={1,2,3}
b={1,2,4}

function on.paint(gc)
if a==b then
gc:drawString("E",0,0,"top")
else
gc:drawString("I",0,0,"top")
end
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 30, 2011, 10:30:54 am
Sadly enough you can't just compare a table like that (unless you add a metatable for it with the appropriate funcion).
You can do it like this:
Code: (Lua) [Select]

function compare(t1, t2)
    for i, p in pairs(t1) do
        if p~=t2[i] then
            return false
        end
    end
    return true
end

a={1,2,3}
b={1,2,3}

if compare(a, b) then
--they are equal
else
--they are not equal
end
Title: Re: Lua Q&A
Post by: pianoman on June 30, 2011, 10:34:40 am
What's "p" in that code?
And what does "in pairs" mean?
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 30, 2011, 11:05:41 am
Its a way to loop through all the items of an Array.

Example: (works only on computer, as it uses print)
Code: (Lua) [Select]
    mytable={1,2,3,"a","b","c"}

    for i, p in pairs(mytable) do
       print("Spot: " . i)
       print("Content: " . p)
    end
will output
Code: (Lua) [Select]
Spot: 1
Content: 1
Spot: 2
Content: 2
Spot: 3
Content: 3
Spot: 4
Content: a
Spot: 5
Content: b
Spot: 6
Content: c

i is the spot in the table, p is the content of that spot.

Here is some handy information about tables: http://lua-users.org/wiki/TablesTutorial
Title: Re: Lua Q&A
Post by: pianoman on June 30, 2011, 03:10:08 pm
Oh, I get it. Thanks, jimbauwens!
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 30, 2011, 04:03:07 pm
No problem :)
Title: Re: Lua Q&A
Post by: pianoman on June 30, 2011, 04:29:31 pm
Sorry, but I have another one:
is there a randint feature in lua?

EDIT: Never mind, I figured it out. :)
Title: Re: Lua Q&A
Post by: pianoman on July 01, 2011, 12:48:58 pm
Is there a way to display what the user is typing (i.e. a text box)?
I have a feeling it uses getText, but I don't know how to use it, and the TI manual is really confusing.
Title: Re: Lua Q&A
Post by: Jim Bauwens on July 01, 2011, 04:03:20 pm
There is a D2Editor, but it really is buggy, so you can't use it.

You can make something like this:
Code: (Lua) [Select]

msg = ""

function on.paint(gc)
    gc:drawString(msg,10,10,"top")
end

function on.charIn(ch)
    msg = msg .. ch
    platform.window:invalidate()
end

Of course you will have to do some changes to make it usable, but it should show the basics.
Title: Re: Lua Q&A
Post by: ExtendeD on July 02, 2011, 04:30:15 am
Try to use the class D2Editor (http://wiki.inspired-lua.org/D2Editor.newRichText).

[edit] sorry I missed jimbauwens's post.

jimbauwens, what's wrong with it? The scrolling?
Title: Re: Lua Q&A
Post by: Levak on July 02, 2011, 10:35:14 am
Try to use the class D2Editor (http://wiki.inspired-lua.org/D2Editor.newRichText).

[edit] sorry I missed jimbauwens's post.

jimbauwens, what's wrong with it? The scrolling?

Because we can't edit it on ClickPad ? (or even I'm stupid)
Title: Re: Lua Q&A
Post by: pianoman on July 02, 2011, 10:56:10 am
Ok, thank you.
Title: Re: Lua Q&A
Post by: ExtendeD on July 02, 2011, 02:06:20 pm
Levak: you mean you can't set the focus on it? A quick try with a single D2Editor on the screen gets the focus on nspire_emu.
Title: Re: Lua Q&A
Post by: Levak on July 02, 2011, 03:30:20 pm
Levak: you mean you can't set the focus on it? A quick try with a single D2Editor on the screen gets the focus on nspire_emu.
I can't. setFocus is a nil value :

Code: [Select]
function on.create()
editor = D2Editor.newRichText()
editor:move(50,50)
editor:resize(200,100)
end
 
function on.charIn(char)
currentText = editor:getText()
editor:setText(currentText .. char) --Add char to the editor
end
 
function on.enterKey()
on.charIn(string.char(10)) --Add a new line
end

function on.tabKey()
if focus then
focus = false
D2Editor.setFocus(false)
else
focus = true
D2Editor.setFocus(false)
end
end

But yes, if I type some keys, it enters the text, OK.

I have thus found another reason to not use the D2Editor : we can't delete it.
Title: Re: Lua Q&A
Post by: Jim Bauwens on July 02, 2011, 03:54:43 pm
The D2Editor also sucks events for some reason, and my programs start acting really weird after a while. I really would like to use it, but its so bugged that I can't. It just get to anoying after a time.
Title: Re: Lua Q&A
Post by: pianoman on July 09, 2011, 07:14:18 pm
Is there a way to resize images in the program?
Title: Re: Lua Q&A
Post by: Levak on July 09, 2011, 07:20:22 pm
Yes :
http://wiki.inspired-lua.org/image.copy
Title: Re: Lua Q&A
Post by: pianoman on July 09, 2011, 07:23:59 pm
Thanks, Levak!
Title: Re: Lua Q&A
Post by: cypressx1 on July 15, 2011, 09:16:46 am
........... function on.paint(gc) .......Text=editor:getText()  gc:drawString(Text,0,0) end   May this work
Title: Re: Lua Q&A
Post by: Jim Bauwens on July 15, 2011, 01:26:39 pm
cypressx1, You can put Lua code in [ code] tag's for better readability :)

Your code is correct, but you must make sure that you have an editor created (D2editor), and that you sometimes invalidate your screen. Also, you should add "top" to your drawString, because now it will be a bit ofscreen:
Code: (Lua) [Select]
gc:drawString(Text,0,0,"top")
Title: Re: Lua Q&A
Post by: cypressx1 on July 18, 2011, 08:22:08 am
Thanks!
Title: Re: Lua Q&A
Post by: Munchor on July 24, 2011, 05:08:06 pm
Has anybody achieved +- smoothscrolling?
Title: Re: Lua Q&A
Post by: fb39ca4 on July 24, 2011, 08:14:32 pm
I know the Copter game had smooth scrolling but then again those graphics were simple.
Title: Re: Lua Q&A
Post by: Jim Bauwens on July 25, 2011, 01:32:06 am
ephan, I have the basis of a game, with smooth scrolling. Its actually intended for the contest, but I haven't had much time to work on it :(
Title: Re: Lua Q&A
Post by: Adriweb on July 26, 2011, 12:31:50 pm
I've made a almost-100%-smooth scrolling engine for a game I wanted to make... it worked pretty well but the game I wanted to make (jumping arcade game, with buildings scrolling, and the character had not to fall between the randomly generated buildings) didn't get really far, so....

Maybe I can find some scrolling functions I have in my backups ... %)
Title: Re: Lua Q&A
Post by: 3rik on August 14, 2011, 01:34:55 am
Does anyone know what the function image.__gc does? When I try to paste code including image.__gc() into the student software, the software closes. I have no idea what this function does. There isn't anything useful in the mere 87 results I had on Google when I searched "image.__gc". When I searched __gc most of it was C++ stuff.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 14, 2011, 03:51:58 am
It's probably a meta method, and is probably not ment to be used in normal scripts :)
Title: Re: Lua Q&A
Post by: 3rik on August 14, 2011, 12:03:14 pm
Thanks. That would probably explain the lack of documentation on it. I'm still curious why the student software just closes instead of giving an error message or something.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 14, 2011, 12:41:49 pm
Well, my guess is that the variable doesn't do error checking, and triggers a reset/crash when invalid parameters are passed.
Title: Re: Lua Q&A
Post by: 3rik on August 14, 2011, 12:48:05 pm
If that's the case then I'm glad I didn't try to send it to my calculator.
Title: Re: Lua Q&A
Post by: NecroBumpist on August 17, 2011, 11:51:13 pm
Does TI utilize LuaJIT (not sure if the ARM port is compatible with this processor) ?
Title: Re: Lua Q&A
Post by: Levak on August 17, 2011, 11:58:16 pm
I don't know, have you got a specific pattern or clue that could help us to determine if it is used ?
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 12:25:27 am
Okay, I can't find my Nspire, and I've yet to update it to 3.0, so if any one can run the following code for me, that would be wonderful.

Code: [Select]
local function test(...)
    if arg then
         print("Lua") -- might have to replace print() with a graphics API call, I haven't use it yet
    else
         print("LuaJIT");
    end
end

test(1, true, 'cool');

LuaJIT handles variable argument functions differently than normal Lua, which is why the above would discern the two.
Sorry, but I don't know the graphics API, as I said, I've yet to start messing around  :)

Also, did TI keep the loadstring() function, or did they clear that out for security reasons ?
If they kept it, it opens the doors for at least one potential exploit, and the possibility of optimized Lua assembly (though TI-Basic is still probably faster)
Title: Re: Lua Q&A
Post by: Levak on August 18, 2011, 12:34:21 am
It returns "LuaJIT"

I'm quite interesting by this, but I don't understand this sentence :
Quote
LuaJIT handles variable argument functions differently than normal Lua, which is why the above would discern the two.
Sorry, but I don't know the graphics API, as I said, I've yet to start messing around

Can you explain a little bit more (as you're there :D)


Quote
Also, did TI keep the loadstring() function, or did they clear that out for security reasons ?
If they kept it, it opens the doors for at least one potential exploit, and the possibility of optimized Lua assembly (though TI-Basic is still probably faster)
It is present, yes =)
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 12:46:35 am
Good, TI finally made a smart decision.  :D
LuaJIT is insanely fast compared to normal Lua.

Quote
Can you explain a little bit more (as you're there )

Having "..." as a function parameter will cause that function to accept any number of inputs.
Lua 5.0.* (I think) was the last version to official support converting of variable arguments into a table which is automatically localized (the 'arg' variable).
Lua 5.1.4 has compatibility with this feature, LuaJIT does not by default (I think you can enable it).

While this is good news for speed, it's bad news for the one exploit I mentioned, as LuaJIT uses a different bytecode format, and the exploit probably isn't viable.
Not to mention I've been working on a complex Lua assembler for other things and when I saw NSpire 3 uses Lua I got excited, but I guess that won't be of much use here  :'(
Title: Re: Lua Q&A
Post by: Levak on August 18, 2011, 12:55:45 am
Having "..." as a function parameter will cause that function to accept any number of inputs.
Lua 5.0.* (I think) was the last version to official support converting of variable arguments into a table which is automatically localized (the 'arg' variable).
Lua 5.1.4 has compatibility with this feature, LuaJIT does not by default (I think you can enable it).

Ok, I see now, thanks for the tip =)
Title: Re: Lua Q&A
Post by: Lionel Debroux on August 18, 2011, 02:30:26 am
TI does not use LuaJIT:
* the first optimized ARM release occurred months after TI started working on Lua in the Nspire OS 3.x;
* LuaJIT is likely to have fixes for the Lua 5.1.4 bugs, while TI's implementation in OS 3.0.1.1753 remained unfixed, see http://ourl.ca/10472 .
Even with a JIT, Lua would remain very far from being a substitute to native code, in terms of both power (expressiveness) and speed.

Some people have expressed worries that if we get native code access (which is perfectly in our right to use the hardware we bought the way we see fit) through Lua, the anti-programmation subset of the management at TI would shut the door on Lua.
But more than four months into Lua programming on the Nspire, and after the making of many programs that dramatically improve the functionality of the Nspire for both educational and gaming uses, it's probably way too late to do that, though... unless they're crazy enough to go the Sony way, and motivate reverse-engineering with a goal of revenge and ghastly attacks on the business model...
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 10:43:31 am
Huh, I guess they must have modified Lua. And that's a good point about the LuaJIT ARM release date, I hadn't even though about that.

Welp,
I dare someone to go run this on their calculator (likely to segfault):
Code: [Select]
loadstring(('').dump(function()X''end):gsub('\2%z%z%zX','\0\0\0'))()

The above is just one of many problems with Lua's bytecode implementation.
I guess now I'll go load OS 3 onto mine, and experiment with a few other bytecode exploits I know of.

Thanks for the info Lionel.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 18, 2011, 11:08:53 am
That above string just error's when I enter it into my calculator. Maybe because its running in a coroutine.
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 11:27:43 am
It should have caused a segfault in the loadstring() function.
It does with normal Lua, maybe it's just not a problem on ARM. Oh well.

Anyway, what software am I supposed to use to update to OS 3 ?
I downloaded the 3.0.2.1791 .tno from TI's website, and the TI NSpire Student Software, but that seems to be a trial, and isn't recognizing my calculator. (then again, I'm not using the cord that came with it)
Any suggestions ?
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 18, 2011, 11:29:38 am
Hm, should work. I didn't have any problems. I hope it isn't because its trial x)
Maybe your cable is a bit damaged?
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 11:31:49 am
That's a possibility.
I couldn't find the original cable, so I stole one from this weird USB-laptop speaker thingy. I'll continue searching for another cable.
Title: Re: Lua Q&A
Post by: Lionel Debroux on August 18, 2011, 11:35:25 am
The cable for connecting the Nspire to the computer is a standard USB A <-> mini-USB B cable :)

BTW, never transfer unmodified OS 3.x versions to a Nspire Clickpad or Touchpad. As described in various news and forum topics here and elsewhere, use TNOC to remove the boot2 3.0 upgrade. It will preserve your ability to downgrade, through DowngradeFix, which is a specially crafted fake OS upgrade exploiting a stack-based buffer overflow in boot2 1.4 to kill the "minimum accepted OS version" information set by OS 2.1.0.631 and 3.0.2.1791 :)
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 18, 2011, 11:37:08 am
Yes, I forgot to mention that. Thanks Lionel :)
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 11:44:03 am
Thanks for the tip, I'm downloading TNOC now.
I also managed to find what I believe is the original cable :D This time my computer recognized the device.
Welp, once I get this on I'll be working on trying out Lua assembly and a few lua bugs on my calc :)

Thanks for the help Lionel and Jimbauwens
Title: Re: Lua Q&A
Post by: Lionel Debroux on August 18, 2011, 11:45:22 am
For direct on-calc testing, you can use oclua; otherwise, use Luna :)
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 11:59:59 am
On calc Lua editing ? Absolutely epic.

Except for TNOC just crashed twice when I tried to patch my OS. Are the final output files supposed to be TNO_WOB2SA files ?
Anyway, after *trying* to remove the boot2 and examples, I get a file that is 7,672KB large, and with an md5 hash of c76b06af603692518b3e2c30131a5380
Is this the right output ?

Edit: I got it to work without crashing, and it produced a .TNO_WOB2SA file, should I just rename this to a .tno file so TI's student software will see it and install it on my calc ?
Title: Re: Lua Q&A
Post by: Lionel Debroux on August 18, 2011, 12:21:28 pm
Quote
I got it to work without crashing, and it produced a .TNO_WOB2SA file, should I just rename this to a .tno file so TI's student software will see it and install it on my calc ?
Yes :)

TNOC crashes pretty often indeed. I've tried to use Valgrind to pinpoint the crash, but there's so much noise in the output (many different causes of improper memory accesses outside of TNOC itself) that it hasn't helped. I'm not sure it would be easy to create meaningful ignore files.

EDIT: I haven't been able to make a meaningful list of suppressions, but
Code: [Select]
valgrind -v --tool=memcheck --num-callers=5 --leak-check=no --malloc-fill=0x55 --free-fill=0xAA ./TNOC_frshows that the code of TNOC 1.21 contains at least one use-after-free error.
When --free-fill=0xAA is passed to valgrind, TNOC cannot open any input file. Tracing the value of variables path and path_2 thusly:
Code: [Select]
else if (error == -2)
{
QMessageBox::critical(this,tr("Attention !"),tr("Fichier Introuvable"));
printf("XYZ \"%s\"\n", path);
printf("XYZ \"%s\"\n", path_2);
}
shows that path is entirely made of 0xAA values...
And, since the only line that modifies path is (because convert_file does not modify its "input" argument):
Code: [Select]
const char* path = LineEdit->text().toStdString().c_str();it means that variable "path" is always invalid in the first place, and that the current code works only accidentally !


Levak ?
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 04:36:56 pm
Wow, this is great! Thanks again for all the help, Lionel and Jimbauwens!
I can't wait to begin exploring some of the API!
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 18, 2011, 04:39:33 pm
I'd suggest you to checkout inspired-lua.org. There most findings/stuff are documented :)
Have fun!
Title: Re: Lua Q&A
Post by: NecroBumpist on August 18, 2011, 08:21:56 pm
When you run a script, and then your calculator immediately reboots itself starting from the Loading OS screen, does that mean you did something wrong  :P ?
Title: Re: Lua Q&A
Post by: zeldaking on August 18, 2011, 08:22:55 pm
I would probably say yes. But then again if I am wrong, punch me.
Title: Re: Lua Q&A
Post by: pianoman on August 18, 2011, 11:28:39 pm
I'm actually not too sure that its your fault, as usually, the program doesn't crash the calulator, it just tells you about the syntax error.
Title: Re: Lua Q&A
Post by: NecroBumpist on August 19, 2011, 12:05:21 am
I'm actually not too sure that its your fault, as usually, the program doesn't crash the calulator, it just tells you about the syntax error.

Oh I'm pretty sure it was my fault.
While doing some ... exploring, I found a __gc() function in the 'val' table, and called that with the table as an arguments, and then my calculator crashed :)
Title: Re: Lua Q&A
Post by: 3rik on August 19, 2011, 01:10:13 am
I was doing a similar thing just a few days ago. I have a hunch it is related to collectgarbage.  (http://www.lua.org/manual/5.1/manual.html Section 2.10.1)

It's probably a meta method, and is probably not ment to be used in normal scripts :)

I agree with jimbauwens, it isn't meant to be used in the script itself.
Title: Re: Lua Q&A
Post by: Scipi on August 23, 2011, 11:21:42 am
How do I clear a string when a certain key is pressed?

I have so far:

Code: [Select]
function on.deleteKey()
    msg = string.char()
    --also used msg = ""
end

But it's not clearing the string or it's not being called.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 23, 2011, 11:23:34 am
You need to use platform.window:invalidate() .
Just put it in the end of the function :)

Edit:
Like this:
Code: (Lua) [Select]
msg = ""

function on.paint(gc)
  gc:drawString(msg, 10, 10, "top")
end

function on.char(ch)
  msg = ch
  platform.window:invalidate()
end

This will show the pressed button
Title: Re: Lua Q&A
Post by: Scipi on August 23, 2011, 11:26:17 am
Didn't work. It's as though it's not calling the function in the first place.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 23, 2011, 11:28:44 am
See my edited post above, shows a little demo :)
Title: Re: Lua Q&A
Post by: Adriweb on August 23, 2011, 11:30:18 am
While doing some ... exploring, I found a __gc() function in the 'val' table, and called that with the table as an arguments, and then my calculator crashed :)
Yep, I wrote that on HackSpire some time ago when we didn't have inspired-lua yet.



and for HOMER-16 :

Code: [Select]
msg = ""

function on.paint(gc)
  gc:drawString(msg, 10, 10, "top")
end

function on.char(ch)
  msg = ch
  platform.window:invalidate()
end

function on.enterKey()
  msg = ""
  platform.window:invalidate()
end
Title: Re: Lua Q&A
Post by: Scipi on August 23, 2011, 11:37:02 am
Thanks, it seems as though deleteKey doesn't work. enterKey did though. :D

Is there a way to just delete the last character in a string?
Title: Re: Lua Q&A
Post by: Levak on August 23, 2011, 12:04:33 pm
Code: [Select]
function on.backspaceKey()
if self.var:len() > 0 then
self.var = string.sub(self.var, 1, self.var:len()-1)
end
platform.window:invalidate()
end

function on.clearKey()
self.var = ""
platform.window:invalidate()
end
Title: Re: Lua Q&A
Post by: Scipi on August 23, 2011, 12:13:44 pm
Thanks Levak. I changed it to
Code: [Select]
function on.backspaceKey()
    if string.len(msg) > 0 then
        msg = string.sub(msg, 1, string.len(msg)-1)
    end
    platform.window:invalidate()
end

function on.clearKey()
    msg = ""
    platform.window:invalidate()
end

And it works perfectly. :D
Title: Re: Lua Q&A
Post by: ExtendeD on August 23, 2011, 12:40:21 pm
Make your code slightly more simple by replacing string.len(msg) with #msg :)
Title: Re: Lua Q&A
Post by: Adriweb on August 23, 2011, 12:48:57 pm
In that case, yep, the # is a good idea, but watch out with tables ! (for key/value tables the count is not what we expect)
Title: Re: Lua Q&A
Post by: Loulou 54 on August 23, 2011, 03:49:32 pm
Thanks Levak. I changed it to
Code: [Select]
function on.backspaceKey()
    if string.len(msg) > 0 then
        msg = string.sub(msg, 1, string.len(msg)-1)
    end
    platform.window:invalidate()
end

function on.clearKey()
    msg = ""
    platform.window:invalidate()
end

And it works perfectly. :D

Oh yes I've already seen this and I wanted to ask some explanations but I forgot ^^ :
The event on.deleteKey seems not working.. The event on.backspaceKey is the one who's called instead, when pressing delete key. Is it normal ?

Thanks !
Title: Re: Lua Q&A
Post by: Scipi on August 23, 2011, 09:40:42 pm
Is there a way in lua to create an object and create multiple instances of it? I've read that there's no class feature so I'm wondering if there's a way to do this.
Title: Re: Lua Q&A
Post by: calc84maniac on August 24, 2011, 12:04:35 am
Here's something I just thought of that should recursively duplicate any table (objects are represented by tables, right?) By recursive, I mean that any element that is a table will be fully duplicated as well.
Code: [Select]
function duplicate(obj)
if type(obj) ~= "table" then
return obj
else
local t = {}
for key,value in pairs(obj) do
t[key] = duplicate(value)
end
return t
end
end

Edit: Added missing then
Title: Re: Lua Q&A
Post by: Levak on August 24, 2011, 04:07:37 am
In Lua, classes are tables, tables of tables etc ..

The Lua classes tutorial is not yet translated on Inspired-Lua, you can try a google translate, but some people says they didn't understand it =/
http://www.inspired-lua.org/2011/05/5-object-classes/

I'm going to sum up

If toto is a class and x,y numbers of this class, f1, f2 functions of this same class, and tab a table also in this class.

Then :
Code: [Select]
toto = {
 x=1,
 y=2,
 f1=function() return true end,
 f2=function() return false end,
 tab={
 .....
 }
}

Then you can access to toto.x, toto.y, etc ...
But this is a fixed way to do "classes".

The TI-Nspire Lua framework contains a function that is not part of Lua 5.1 : class()

This function avoids typing multiple lines that many of us won't understand (even if it is quite simple)

With the same example :

Code: [Select]
toto = class()

function toto:init()
 self.x, self.y = 1, 2
 self.f1 = function() return true end
 self.f2 = function() return false end
 self.tab = {...}
end

init() function is required by class(). When you want to create a new toto object, you will do like this : a = toto()
You can give to init() arguments to create a specified object like this :


function toto:init(x0, y0)
 self.x, self.y = x0, y0
 self.f1 = function() return true end
 self.f2 = function() return false end
 self.tab = {...}
end

Then, you will be able to do : a = toto(1,2) and access to a.x and a:f1

Remember another thing in Lua : the difference between . and : between the object and its element :

a.x access to x element in object a
a.f1() access to f1 function in object a
a:f1() access to f1 function in object a and gives to f1 function a as first argument, that way you can use 'self' in its définition.

a.f1(a) == a:f1()
function a.f1(parent) return parent.x end == function a:f1() return self.x end
Title: Re: Lua Q&A
Post by: insertcoolnamehere on August 28, 2011, 08:23:19 pm
Simple question: Why doesn't this work?

Code: [Select]
function creategamedata()
    screen = "loading"
    local t1, t2
    for t1 = 1, gamelen, 1 do
        for t2 = 1, t1, 1 do
            gamedata[t1][t2] = math.random(1,4)
        end
    end
    game()
end

This is the error:

(http://i.imgur.com/jbDjK.png)

What it is supposed to do is create a table:

{{1}, {1,2}, {1,2,3}, ....} (the numbers are randomized, those were examples)

I have defined 'gamedata' somewhere else like so:

Code: [Select]
gamedata = {}
If you want the whole code for the game (simon), then just ask. I don't want to post it unnessecarily

EDIT: Line 19 is this one:
Code: [Select]
           gamedata[t1][t2] = math.random(1,4)
Title: Re: Lua Q&A
Post by: 3rik on August 28, 2011, 08:30:53 pm
gamedata's value for gamedata[t1] is nil. You are trying to access it like a table. You would either have to put gamedata[t1]={} or table.insert(gamedata, {}) between the fors.
Title: Re: Lua Q&A
Post by: NecroBumpist on August 28, 2011, 08:30:55 pm
Simple question: Why doesn't this work?

The simplest questions deserve the simplest answers.
You're attempting to write to a table that doesn't exist.

Assuming gamedata is just an empty table, this code should work:

Oh yeah, I removed some redundancies.
Code: [Select]
function creategamedata()
    screen = "loading"
    local rand = math.random;

    for t1 = 1, gamelen do
        local v = {};
        gamedata[t1] = v;

        for t2 = 1, t1 do
            v[t2] = rand(1,4)
        end
    end

    game()
end
Title: Re: Lua Q&A
Post by: insertcoolnamehere on August 28, 2011, 08:34:39 pm
Thanks guys! And Necro, your code works perfectly! Today's my first day on lua so kinda confused :)
Title: Re: Lua Q&A
Post by: insertcoolnamehere on August 28, 2011, 11:15:29 pm
Another question:

How do I get Lua to do something, wait (say, 1 second), and do something else? I want to do this repeatedly and what I saw on the Inspired-Lua wiki didn't please me. (Was a little complicated and would be hard to duplicate)

http://wiki.inspired-lua.org/timer.getMilliSecCounter
 (http://wiki.inspired-lua.org/timer.getMilliSecCounter)

Anyone got any suggestions?
Title: Re: Lua Q&A
Post by: NecroBumpist on August 28, 2011, 11:25:53 pm
You could use timers.

Code: [Select]
-- since I don't know if you can pass the on.timer() function endless arguments, we'll store them in a local

local timerFunction;

function on.timer()
    timer.stop();
    assert(timerFunction)();
end

local function wait(s, f)
    timerFunction = f;
    timer.start(s);
end

wait(1, function()
    -- whatever you want to do in 1 second
end)
Title: Re: Lua Q&A
Post by: Levak on August 28, 2011, 11:44:15 pm
Don't forget to stop the timer with timer.stop() if you don't want to repeat it each second =)
Title: Re: Lua Q&A
Post by: 3rik on August 28, 2011, 11:50:46 pm
Well after using timer.start(1) the function on.timer will be called every second. So whatever you define on.timer to do will happen every second until you use timer.stop(). You can change how frequently  on.timer is called by changing the argument. So timer.start(0.5) will call on.timer every 0.5 seconds. Make sure not to put so much stuff in on.timer that it doesn't keep time properly.
For example, the following code is for a simple stopwatch. Press enter to start and reset it.

Code: [Select]
Seconds, Mode = 0, "Not Timing" --[[Sets default values to Seconds and Mode]]
function on.enterKey() --[[This is called when ever the enter key is pressed]]
if Mode == "Not Timing" then --[[If the mode is "Not Timing" when enter is pushed this restets the Seconds counter, switches the mode to "Timing" and starts the timer (counting at 0.1 seconds)]]
Seconds = 0
Mode = "Timing"
timer.start(0.1)
else --[[If the mode wasn't "Not Timing" switch it to "Not Timing" and stop calling on.timer]]
Mode = "Not Timing"
timer.stop()
end
end
function on.paint(gc) --[[This is called every time the calculator needs to refresh the screen]]
gc:drawString(tostring(Seconds), 0, 0, "top") --[[This displays what the value of the Seconds Counter is]]
end
function on.timer() --[[When Mode is "Timing" this will be called every 0.1 seconds]]
Seconds = Seconds + 0.1 --[[Increases the number of seconds counted]]
platform.window:invalidate() --[[Forces the screen to refresh and call on.paint so the number of seconds gets updated on the screen]]
end

Ninj'd
Apparently people typed their responses before I was done. Oh well. I'll post it anyway.
Title: Re: Lua Q&A
Post by: insertcoolnamehere on August 29, 2011, 09:11:46 am
Hmm... so a timer invokes the on.timer() event every time it fires until timer.stop()? Haven't seen that before! :)
Title: Re: Lua Q&A
Post by: Adriweb on August 29, 2011, 09:21:01 am
yep.

It's useful that way for games, for example, that require constant screen refreshes :)
Title: Re: Lua Q&A
Post by: ExtendeD on August 29, 2011, 10:22:37 am
The TI-Nspire event-driven API makes sure the Lua programs work well in the multi-task environment of the TI-Nspire, so you won't see any blocking function such as sleep(). This may be a bit disturbing but you should soon get used to it. We can help you with this if you give more details on why you want your program to wait.
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 29, 2011, 03:59:42 pm
Talking about sleep(), its relatively easy to implant by mixing a coroutine and the timer. sleep can be kinda usefull for people making a text adventure :)
Title: Re: Lua Q&A
Post by: pianoman on August 29, 2011, 06:02:28 pm
How do we get the cursor to show up on the screen? I tried cursor.show(), but it only displayed the cursor for about half a second, then vanished.
Title: Re: Lua Q&A
Post by: NecroBumpist on August 29, 2011, 06:34:43 pm
pianoman, have you tried adding cursor.show() to on.draw() ?
Title: Re: Lua Q&A
Post by: pianoman on August 29, 2011, 06:36:35 pm
Yup, I put it in on.paint(gc).
Title: Re: Lua Q&A
Post by: Adriweb on August 29, 2011, 06:38:43 pm
Talking about sleep(), its relatively easy to implant by mixing a coroutine and the timer. sleep can be kinda usefull for people making a text adventure :)
I'd be curious to see that code :P


and @pianoman : you never call cursor.hide() ?
Title: Re: Lua Q&A
Post by: Levak on August 29, 2011, 07:48:24 pm
TI-Nspire ClickPad ?

As I remember my first tests, it was impossible to show the cursor on ClickPad
Title: Re: Lua Q&A
Post by: pianoman on August 29, 2011, 09:28:50 pm
@Adriweb: Nope, never.
@Levak: Yes, I have that, but in other programs, like Towers of Hanoi, the cursor works... could I just make my own cursor and have it move around when the mouse is used?
Title: Re: Lua Q&A
Post by: Levak on August 29, 2011, 10:26:02 pm
Ok, so it seems that putting a cursor.show in on.create() and on.resize does it...
I can't test right now.
Title: Re: Lua Q&A
Post by: pianoman on August 29, 2011, 10:28:51 pm
Putting it in both?
Ok, I'll test that once I finish my vocab homework :P
Title: Re: Lua Q&A
Post by: Jim Bauwens on August 30, 2011, 03:00:45 am
... could I just make my own cursor and have it move around when the mouse is used?
Yes, I think that might be possible, hiding the real one and showing yours.
Title: Re: Lua Q&A
Post by: pianoman on August 30, 2011, 10:50:04 pm
Ok, so it seems that putting a cursor.show in on.create() and on.resize does it...
I can't test right now.
Nope, nothing. :(
Title: Re: Lua Q&A
Post by: Levak on September 03, 2011, 04:05:51 am
Levak ?

Thanks.
TNOC 1.22 I released today fixes thoses memory bugs =)
And also it finaly renames correctly files \o/

http://tiplanet.org/forum/archives_voir.php?id=1922 (same link as before)
Title: Re: Lua Q&A
Post by: Sebasu on October 03, 2011, 07:21:04 pm
Hello I'm starting with lua, i have a curious problem:
my code:
function on.paint(gc)
    gc:drawString("Vagos CORP®", 5, 25)
    gc:drawString("Organisación Industrial", 5, 45)
    gc:drawString("Desarrollado por Sebasu", 5, 205)
end
when I copy to oclua it works perfectly but when i save the oclua file and exit, the compiled program dissapears of the screen in the file.
when I use the TI-Scriping Tool and paste the generated code, the TI-Soft close inmediately.
when I use luna 0.2a it generates te .tns file but when i open the file:  "3: ')' expected near 'Organisaci36'"
With one hour testing, I think that the simbols "®" and "ó" are the problem but I need this simbols working
how can i do that?
and what is the real problem?
thanks for help
and luna 0.2a can be downloaded from here http://ndlessly.wordpress.com/
Title: Re: Lua Q&A
Post by: pianoman on October 03, 2011, 10:14:00 pm
Hi!
Okay, this might seem a bit complex, but its actually pretty simple.
1. Go to Scratchpad and type in ord("®"). Record the number it outputs, then repeat for "ó".
2. To get those strings, you will need to do this:
Code: [Select]
a="Vagos CORP"..math.eval("char(whatever number ® output)")
b="Organisaci"..math.eval("char(the output from ó)").."n Industrial"

Now you can just print those strings like this:
Code: [Select]
function on.paint(gc)
    gc:drawString(a,5, 25)
    gc:drawString(b, 5, 45)
    gc:drawString("Desarrollado por Sebasu", 5, 205)
end
That's it (I think :))
Title: Re: Lua Q&A
Post by: ExtendeD on October 04, 2011, 11:09:26 am
You can also use:
gc:drawString("Vagos CORP" .. string.char(the number returned by ord))
I'm not sure what's wrong with oclua and the TI-Nspire Scriping Tools. But a problem was already reported with Luna v0.2 when converting special characters, I'll look into it.
Title: Re: Lua Q&A
Post by: Sebasu on October 04, 2011, 03:38:28 pm
wow so interesting, pianoman it works perfectly!!!
the ExtendeD's Solution was logic but when execute the generated file, it show me random "unicode" simbols, i don't know if is a compiler problem or the algorithm need to be corrected
thanks for help
luna0.2a still has bugs and with the TI-Scriping Tool can be compiled, but large programs can't be pasted in the TI-Soft or in oclua (too big for the memory)
it's so frustrating!!!!!
Title: Re: Lua Q&A
Post by: Levak on October 04, 2011, 04:06:07 pm
string.uchar() I guess ?
Title: Re: Lua Q&A
Post by: Sebasu on October 05, 2011, 12:59:27 am
wow amazing!!!
and it correct an error compiling in luna my large code with this chars
thanks for help Levak
Title: Re: Lua Q&A
Post by: pianoman on October 05, 2011, 06:03:54 pm
Hey, i could use that, Levak :D/me slaps himself with a netham for not thinking of that
Title: Re: Lua Q&A
Post by: Scipi on October 05, 2011, 07:40:37 pm
I have a question about the tool palate. Am I able to use it to get two separate input fields on a single menu?
Title: Re: Lua Q&A
Post by: NecroBumpist on October 05, 2011, 08:20:32 pm
How does grayscale work on the non CX calcs ? More importantly how do I use it ?
How many levels of grayscale does the normal NSpire support ?
How does this work with the TI-Image format ?

I'm asking since I'm writing a .BMP file -> TI-Image file convert for easy Lua usage.
Title: Re: Lua Q&A
Post by: calc84maniac on October 05, 2011, 11:32:52 pm
How does grayscale work on the non CX calcs ? More importantly how do I use it ?
How many levels of grayscale does the normal NSpire support ?
How does this work with the TI-Image format ?

I'm asking since I'm writing a .BMP file -> TI-Image file convert for easy Lua usage.

TI-Image is always in 16-bit color format, and on the grayscale calculators it is converted automatically. Oh, and there are 15 shades of grayscale, since you wanted to know.
Title: Re: Lua Q&A
Post by: pianoman on October 05, 2011, 11:33:37 pm
How does grayscale work on the non CX calcs ? More importantly how do I use it ?
How many levels of grayscale does the normal NSpire support ?
How does this work with the TI-Image format ?

I'm asking since I'm writing a .BMP file -> TI-Image file convert for easy Lua usage.
I think the official tool does that, but if you would like to as well, more power to you!
Title: Re: Lua Q&A
Post by: Jim Bauwens on October 06, 2011, 01:41:19 am
TI-Image is always in 16-bit color format, and on the grayscale calculators it is converted automatically. Oh, and there are 15 shades of grayscale, since you wanted to know.
TI.Image is actually 15 bit color, and one alpha bit.

Check out the (outdated) info on Inspired Lua, and the official documentation, they should be clear enough.
You can also check out my python converter at http://bwns.be/jim/convert.py. It's pretty easy to understand :)

@homer, I don't understand your question fully, mind explaining a bit more? :D
Title: Re: Lua Q&A
Post by: Scipi on October 06, 2011, 12:00:44 pm
Basically I want to know if I can use the tool palate to create a menu with an area where you can input a number or character.
Title: Re: Lua Q&A
Post by: Jim Bauwens on October 06, 2011, 12:59:06 pm
I don't think so, the tool palette is quite limited, so you will have to make your own.
I recommend you to check out Levak's Sudoku code, where he implemented a "screen manager". This will be of big help if you want to make your own menu system (and other stuff).
Title: Re: Lua Q&A
Post by: Sebasu on October 26, 2011, 05:37:54 pm
Hello, i wanta to make an screen with areas to input numbers, i have checked the levak's sudoku code but i can´t understand completely, can somebody make me an example?
it would be a big help
Title: Re: Lua Q&A
Post by: Jim Bauwens on October 27, 2011, 03:03:22 am
Do you mean like a textbox?

Code: (Lua) [Select]
msg = ""

function on.paint(gc)
  gc:drawString(msg, 10, 10, "top")
end

function on.charIn(ch)
  msg = msg .. ch
  platform.window:invalidate()
end

What happens here is that on.charIn get called everytime you press a character key. We then add the character to the variable msg and invalidate the screen.
Because we invalidated the screen, on.paint() gets called and displays the string on the screen :)
Title: Re: Lua Q&A
Post by: Sebasu on October 30, 2011, 06:13:10 pm
wow amazing
simpler than I thought
thanks jimbauwens
Title: Re: Lua Q&A
Post by: Jim Bauwens on October 30, 2011, 06:14:11 pm
Glad I could be a help :)
Title: Re: Lua Q&A
Post by: Lakuuni on November 06, 2011, 12:13:50 pm
I'm quite new to lua and I've just started to do my own simple experiments with it to get the gist of the language and programming for calculator. Now I'm trying to figure out how to get input from the user via nspire's keyboard. To do that I've tried exploring lua.org, hackspire wiki, google and lua programs posted on this forum, but when trying to create a simple program that would for example print "hello world" when the user presses the enter key, it seems to notice the enter being pressed only when pressing it after for example catalog button. This obviously isn't very useful when planning real projects so I ask you to guide me to a batter way of achieving communications between program and it's user.
Here's the code I tried:
Code: [Select]
function on.enterKey()
function on.paint(gc)
gc:drawString("Hello World!",0,0,"top")
end
end
Title: Re: Lua Q&A
Post by: Levak on November 06, 2011, 12:23:33 pm
This will work, but it is really dirty :P
You forgot to use platform.window:invalidate() that indicates the Nspire framework you want to refresh teh screen (note that on.paint is not called as soon as you call platform.window:invalidate() )

This will work :

Code: [Select]
function on.paint(gc)
if hello then
gc:drawString("Hello World!", 0, 0, "top")
end
end

function on.enterKey()
hello = true
platform.window:invalidate()
end

Have you looked at http://inspired-lua.org ?
Title: Re: Lua Q&A
Post by: 3rik on November 06, 2011, 12:37:35 pm
When you start an Nspire Lua program, the calculator goes through the program and initializes any functions or variables and runs any instructions outside a function. Then it continues to loop through the event functions. In your example, when the program starts, on.enterKey() is initialized. When the enter key is pressed, the on.enterKey function is called. The on.paint function is defined here instead of having it be defined at the beginning. But the on.paint function is only called by the calculator when the window is "invalidated." The window starts out invalidated but becomes valid after the on.pain function is called. Moving the cursor or opening the catalog invalidates the screen and this is why your function works the way it does. To purposely invalidate the window (thus calling on.paint at the end of the current function) you can use the platform.window:invalidate() function. To summarize all this, here is code that accomplishes what you were trying to do.

Code: [Select]
enterHasBeenPressed = false --initializes enterHasBeenPressed to be false
function on.paint(gc)
if enterHasBeenPressed then --exicute the following code if enterHasBeenPressed is true
gc:drawString("Hello World", 0, 0, "top")
end
end
function on.enterKey()
enterHasBeenPressed = true --Since enter has been pressed enterHasBeenPressed is now true
platform.window:invalidate()        --invalidates the window so when on.enter is done on.paint will be called
end
Having events being called takes a bit to get used to if you're used to a purely sequental language, but if you keep trying, you'll catch on. ;)
Also if you haven't already, introduce yourself here (http://www.omnimaga.org/index.php?board=10.0).
Welcome to Omnimaga! :D


Edit: Ninja'd

I suppose enterHasBeenPressed doesn't actually need to be set to false at the beginning but explicitly telling it to be false is good for other humans reading it. Both ways work.

Also remember that just because you've initialized a function, it doesn't mean it will be called. The special event functions (like on.paint) are tricky because in simple programs this seems to be the case.
Title: Re: Lua Q&A
Post by: Adriweb on November 06, 2011, 03:27:14 pm
You cal also do that, if you want the text to appear/disappear when pressing enter multiple times :

Code: [Select]
enterHasBeenPressed = false --initializes enterHasBeenPressed to be false
function on.paint(gc)
if enterHasBeenPressed then --execute the following code if enterHasBeenPressed is true
gc:drawString("Hello World", 0, 0, "top")
end
end
function on.enterKey()
enterHasBeenPressed = not enterHasBeenPressed -- will become true if false and false if true (switch state)
platform.window:invalidate()         --invalidates the window (basically, on.paint will be called)
end
Title: Re: Lua Q&A
Post by: Lakuuni on November 07, 2011, 11:27:27 am
Great thanks to all of you, Levak, 3rik and Adriweb. I don't know what I would do without you guys helping me take my first steps. You've been really helpful.
Title: Re: Lua Q&A
Post by: Adriweb on November 07, 2011, 12:29:35 pm
No problem :)
Title: Re: Lua Q&A
Post by: renatose on November 27, 2011, 06:52:23 pm
Is there any lua function to call nspire's BASIC commands?

It would ease my life a lot if I could use Text and Request commands...
Title: Re: Lua Q&A
Post by: 3rik on November 28, 2011, 12:18:44 am
As far as I'm aware, commands that are usable by functions can be accessed using math.eval() but commands like Request and Text are only available in programs.

Visit http://ourl.ca/12647 (http://ourl.ca/12647) for more information.

An example of the usage of math.eval is located here: http://www.inspired-lua.org/2011/08/save-a-high-score-without-cheating-possibility/ (http://www.inspired-lua.org/2011/08/save-a-high-score-without-cheating-possibility/)

Quote from: Nspire Scripting Application Programming Interface
Code: [Select]
math.eval(math_expression)This function sends an expression or command to the Nspire math server for evaluation. The input expression must be a string that the Nspire math server can interpret and evaluate.
If the math server successfully evaluates the expression, it returns the numerical results. The eval function returns no result if the math server does not return a calculated result or if the calculated result cannot be represented as a fundamental Lua data type.
If the math server cannot evaluate the expression because of a syntax, simplification, or semantic error, eval returns two results: nil and an error number.
Title: Re: Lua Q&A
Post by: Jim Bauwens on November 28, 2011, 03:04:39 am
Indeed, math.eval() allows you to run quite some basic functions, but Request and Text are not available.
It isn't too hard to program it though, once you get the hang of Lua on the nspire.
The best way would be to implant a Screen Manager (hint, Levak's sudoku), that easily allows you to have different 'screens'.
Then just make a screen for a popup, and you are done :)
Title: Re: Lua Q&A
Post by: renatose on November 28, 2011, 05:07:06 pm
Ok, thank you 3rik and jimbauwens. So what you're telling me is that I can call virtually any basic function except the commands I want to... Right?

I'll take a look at Levak's Sudoku then we'll see if I can do it.
Title: Re: Lua Q&A
Post by: epic7 on January 06, 2012, 07:14:57 pm
Not a very active topic, it seems :P

Ok, I want to draw a game board. I tried using fillRect, filArc and such but I'm a total failure at it.

Nick says not to use ti-image because it will be really slow...

Is there any other way?
Title: Re: Lua Q&A
Post by: 3rik on January 06, 2012, 11:18:22 pm
If you have the choice between fillRect, fillArc, or fillPolygon and drawImage, I'd go with the fill functions. Obviously if you want some intricate pattern on the screen it is ridiculous to put hundreds of fillRects but if it is something relatively simple then it is usually a good choice. Personally I've only noticed a speed difference when there's a lot of images being drawn, however, images take up a bunch of memory compared to fillRect.

If you want to just draw a simple chess board you could do something like this:

Code: [Select]
function on.paint(gc)
gc:setColorRGB(0, 0, 0)
draw = false
for column=1, 8 do
draw = not draw
for row=1, 8 do
draw = not draw
if draw then
gc:fillRect(column * 25 - 19, row * 25 - 19, 25, 25)
end
end
end
gc:drawRect(5, 5, 201, 201)
end

I'm not sure if I answered your question but I hope this helps.
Title: Re: Lua Q&A
Post by: epic7 on January 06, 2012, 11:19:10 pm
I got it already using a bunch of shapes, but thanks anyways :)
Title: Re: Lua Q&A
Post by: Munchor on June 13, 2012, 10:42:50 am
Can LÖVE be used on the Nspire?
Title: Re: Lua Q&A
Post by: Jim Bauwens on June 13, 2012, 10:48:58 am
The syntax is very similar, it will be not too hard to port programs. But Love has certain functions that can not be created easily in the Nspire API.
It would be possible how to create a runner that runs simple love games (in pure lua).

Edit: it would be definitely possible if you get some help of extLua :P
Title: Re: Lua Q&A
Post by: Jonius7 on September 22, 2012, 11:28:53 pm
This may have been mentioned before, but is it possible to do anything similar to Request and RequestStr in TI-nspire Basic on Lua?
I want the user to be able to input a few numbers, and see what number they are typing I guess.

If not I can work around with pressing "up" and "down" buttons to change these numbers in the program, but I'll just have to change the programming around a bit.
Title: Re: Lua Q&A
Post by: cyanophycean314 on September 23, 2012, 05:06:00 pm
Yeah, it's kinda annoying not to have one. There was an article on Inspired Lua about it: http://www.inspired-lua.org/2011/12/how-to-have-a-nice-little-input-function-in-lua/ (http://www.inspired-lua.org/2011/12/how-to-have-a-nice-little-input-function-in-lua/)
Title: Re: Lua Q&A
Post by: Jonius7 on September 24, 2012, 02:19:54 am
Ok I have an idea to just capture certain characters the user types and display them separately but concatenated as a single string.
EDIT: Oh yes that's what I was looking for thanks cyano.
Title: Re: Lua Q&A
Post by: Adriweb on September 24, 2012, 05:44:02 am
And if you're looking to implement that into a string manager, here's an example :
https://github.com/adriweb/EEPro-for-Nspire/blob/master/Global%20Libraries/widgets.lua#L145
Title: Re: Lua Q&A
Post by: Bindle on November 18, 2012, 09:50:44 am
Hey guys, Im coding a game.

When I type xp = xp + 1 in the function SceneUpdate() my xp just turns away into a million xp points. I just want the increasment of one.

How do I do that?

Bindle
Title: Re: Lua Q&A
Post by: Adriweb on November 18, 2012, 09:55:59 am
You're probably calling SceneUpdate() too often, then.
If SceneUpdate() is used to update graphical parts, don't increment the xp in there, rather in another function you call whenever it's needed :)
Title: Re: Lua Q&A
Post by: Bindle on November 18, 2012, 09:59:08 am
So where do I do that? Is this the way to call a function?

function SceneUpdate()
   if wormhp == 0 then run("level")
   end
end
   
function level()
   xp = xp + 1
   return
end
Title: Re: Lua Q&A
Post by: Levak on November 18, 2012, 06:11:02 pm
Simply do

Code: [Select]
function SceneUpdate()
if wormhp == 0 then
level()
end
end

function level()
xp = xp + 1
end
Title: Re: Lua Q&A
Post by: mannuri on February 24, 2013, 08:28:55 am
Hi all,

I think some of you have heard about timasterbox, http://code.google.com/p/timasterbox/ (http://code.google.com/p/timasterbox/).
The autor seems to be busy so im leave my question here.
Im not a lua programer, but im triing to creat my school programs using that tool.
My problem is How i get the values imputed at numberBox. I want use the comand var.store() but i dont know what is the imput table name.

When i put an image into lua string i lost to mush quality. Can someone show a way to keep most of that quality.

Please LuaGod's help me  :P
Title: Re: Lua Q&A
Post by: jwalker on February 24, 2013, 09:02:04 am
I don't know how his calls work, but with my lib and actually with any variable storage you can do var.store("varName", NumericUpDown_Name.num).
Title: Re: Lua Q&A
Post by: mannuri on February 24, 2013, 10:23:32 am
Thanks, i know how to use var.store() i dont know what is the  NumericUpDown_Name.num name.

Code: [Select]
if widgetNoFocus == false then
            if self.widgets[self.widgetFocus].typeBox == "NumberBox" then
                -- Concatenamos el nuevo caracter.
                self.widgets[self.widgetFocus].text = self.widgets[self.widgetFocus].text .. char

i have many NumberBox, and the self.widgets[self.widgetFocus].text is the variable i think (learn from Nspire tutorial)

At start is some close to this:
Code: [Select]
    numberBoxj = NumberBox(70, "CENTER")
    numberBoxL = NumberBox(70, "CENTER")

    MASTERBOX:addWidget(numberBoxj)
    MASTERBOX:addWidget(numberBoxL)

and i want store the var from numberBoxj into "j".
Title: Re: Lua Q&A
Post by: jwalker on February 24, 2013, 10:27:22 am
that is your variable. The NumericUD is just a control from my lib. So for number box it may be var.store("variable", NumberBox_Name.text).
Title: Re: Lua Q&A
Post by: mannuri on February 24, 2013, 11:12:11 am
Thanks,

If i use:
Code: [Select]
var.store("qi",NumberBox[numberBoxQ].text)I got that error:
Code: [Select]
attempt to index field '?' (a nil value)
If i use:
Code: [Select]
var.store("qi",NumberBox_numberBoxQ.text)I got that error:
Code: [Select]
attempt to index global 'NumberBox_numberBoxQ' (a nil value)
 :'(
Title: Re: Lua Q&A
Post by: mannuri on February 24, 2013, 11:36:29 am
Yeahh, thank you guys!  ;D

Im just putting the var.store at bad place  :w00t:
Title: Re: Lua Q&A
Post by: DJ Omnimaga on February 24, 2013, 12:05:36 pm
Heya and welcome here. I think I saw this software on Ticalc.org recently. It seemed pretty nice in general. There is also wzGUILib but I think that is for C programmers.

Good luck! :)
Title: Re: Lua Q&A
Post by: mannuri on February 24, 2013, 12:50:55 pm
People dont like to call programs like prog() and nspire dont have the dialog comand like voyage 200, i know a bit about ti basic but nothing about lua. So that tool is amazing because it solve the imput problem. Now i can prob to my friends Nspire is better than voyage 200. :)
Title: Re: Lua Q&A
Post by: jwalker on February 24, 2013, 03:07:32 pm
Heya and welcome here. I think I saw this software on Ticalc.org recently. It seemed pretty nice in general. There is also wzGUILib but I think that is for C programmers.

Good luck! :)

Nope, its lua. Although I have thought about porting it to C to give it more power.
Title: Re: Lua Q&A
Post by: Jonius7 on July 17, 2013, 05:20:56 am
what does __varname mean?

example:
Code: [Select]
-- Class definition system
class = function(prototype)
    local derived = {}
    local derivedMT = {
        __index = prototype,
        __call  = function(proto, ...)
            local instance = {}
            local instanceMT = {
                __index = derived,
                __call = function()
                    return nil, "attempt to invoke an instance of a class"
                end,
            }
            setmetatable(instance, instanceMT)
            if instance.init then
                instance:init(...)
            end
            return instance
        end,
    }
    setmetatable(derived, derivedMT)
    return derived
end
Title: Re: Lua Q&A
Post by: ElementCoder on July 17, 2013, 06:04:18 am
From the manual:
"Metatables control the operations listed next. Each operation is identified by its corresponding name. The key for each operation is a string with its name prefixed by two underscores, '__'; for instance, the key for operation "add" is the string "__add"."

It's like operator overloading. You can define custom behaviour this way.

I'm not 100% sure as it's been a long time since I've done anything with Lua. I also think it had something to do with global variables as well, but that may not be true.

[Edit:] I meant not sure :P
Title: Re: Lua Q&A
Post by: Jonius7 on July 17, 2013, 11:05:08 pm
How do you reference a particular value in an array, like a matrix (such as in TI-BASIC, Casio Basic)

Here's an example array:

Code: [Select]
eg = {{1,1,1,2,2,1,3,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,2,2,2,3,1,3,3,1}
,{1,1,2,2,2,1,3,3,1,1,2,3,3,3,3,3,1,1,1,2,2,2,2,2,3,3,3,3,3,3,1}
,{1,1,3,3,3,1,1,1,3,3,3,3,3,1,1,1,2,2,2,2,2,3,3,3,3,3,3,1,2,2,2}
,{1,1,3,3,3,1,3,3,3,2,2,2,1,3,1,2,3,1,3,2,3,1,3,2,1,3,3,1,1,2,1}
,{2,2,3,3,3,3,3,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,1,1,1}
,{2,1,3,2,3,1,3,3,1,1,2,2,2,2,1,1,1,1,1,2,1,2,2,3,3,1,2,3,1,2,3}
,{3,3,1,1,1,2,2,2,3,1,1,3,2,1,3,2,1,1,1,2,2,1,2,2,3,2,3,3,3,3,1}
,{3,1,2,3,3,2,1,3,1,2,3,1,3,1,2,2,1,2,1,2,3,1,2,3,1,2,3,1,2,3,1}}
How would I for example reference the 1 in the 4th row, 6th column?

Or am I not thinking in Lua programming terms and this shouldn't be used?

I've tried eg[4][6] and eg [4,6] but they didn't seem to work.
Title: Re: Lua Q&A
Post by: Jonius7 on July 17, 2013, 11:23:59 pm
Never mind I figured it out. The correct way is
eg[4][6]

It was another bug in the code that was holding it back.
Sorry for double post.

PS: This code, I'll be releasing soon as a new project, but I don't want to reveal anything until I make further progress :)
Title: Re: Lua Q&A
Post by: Jonius7 on July 21, 2013, 02:26:57 am
So I think I need a bit more explanation with Lua classes. I got interested in them when I was trying to understand the owllibrary code. http://ourl.ca/14610

It had all this syntax that I didn't quite understand and the ordering and many cross-references between functions got me confused. So I read a bit of stuff on wiki, inspired-lua tutorials, some omnimaga topics and compasstech (not intently though, I kinda got it, but maybe not enough to use it)

so from what I gathered, here's an example with code taken from owllibrary.

Code: [Select]
Coyote = class()

function Coyote:init(x, y, width, height, options)
    options = options or {}
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.tiles = {}
    self.controls = options.controls or {up = "up",
                                         down = "down",
                                         left = "left",
                                         right = "right"}
    self.player = {}
    self.tileSize = options.tileSize or 16
    self.scrollThreshold = options.scrollThreshold or 1
    self.outOfBoundsColor = options.outOfBoundsColor or {0, 0, 0}
    self.tileCount = 0
end



Q1: This is more of a confirmation. Does self refers to the classname itself? So self.x would refer to Coyote.x in this case? Likewise for the others?

Q2: What does . refer to? From what I gather it would mean it would add it to a list/table so that if Coyote was called up, you'd get Coyote == {"x"==x, "y"==y, "tiles"=={} etc...}. Is this right?

Q3: How does or affect the variable assigning? in self.controls = options.controls or {up = "up", down = "down", left = "left", right = "right"}, does that mean self.controls becomes both possible values? This is one I'm stumped on

Q4: Also another one, I've never been very confident in what return means (even though I've encountered it in several languages such as JavaScript. I've known it to return a value if it refers to a variable but it seems that elsewhere in the code it can represent some other things too? Clarification?

Q5: Generally I don't understand classes enough, I don't think I finished reading through the inspired lua tutorial though. Might go back and read it ;D

Thanks for your help in advance.
Title: Re: Lua Q&A
Post by: Levak on July 21, 2013, 08:11:15 am
Q1: This is more of a confirmation. Does self refers to the classname itself? So self.x would refer to Coyote.x in this case? Likewise for the others?
The real meaning of "self" is the first argument passed to the function. When using ":" instead of "." (i.e : foo:bar() ) the object (here "foo") is passed as frst parameter :
Code: [Select]
foo:bar() === foo.bar(foo)
Thus, it refers to the instance of the object using that function, but it can be used for other purposes, such as using a "static" method of the class (I may be unclear on that ... sorry) :
Code: [Select]
Foo = class()
function Foo:init()
  self.i = 69
end
function Foo:bar(i)
  print(i, self.i)
  self.i = i
end
foo = Foo()
foo:bar(42) -- calls Foo.bar(foo, 42) ; prints 42 69
foo:bar(42) -- prints 42 42
print(Foo.i)  -- nil
Foo:bar(42) -- calls Foo.bar(Foo, 42) ; prints 42 nil
print(Foo.i) -- prints 42

Q2: What does . refer to? From what I gather it would mean it would add it to a list/table so that if Coyote was called up, you'd get Coyote == {"x"==x, "y"==y, "tiles"=={} etc...}. Is this right?
Basic : classes in Lua are reprensented as tables.
"." let you access to one element (defined of not) of a table. In Lua tables are associatives using all sort of hash key (you can use functions or tables as hash key). In general you access an element using its key with [ and ] such as :
Code: [Select]
t = {foo=bar1, ["foo with spaces"]=bar2}
t["foo"] -- bar1
t["foo with spaces"] -- bar2
t.foo -- bar1
As you can see, since "foo" is a valid identifier, it can be used with the "." convention.

There are multiple ways to add an element in the table, and it depends if you're seeing the table as a contiguous array (such as in C) or associatives ones.
It depends when you're using #t or ipairs/pairs(t). For example IIRC you cannot use #t or table.getn(t) on tables you filled with . or [] although you can iterate through using ipairs/pairs.

So, as you may understood, this :
Code: [Select]
t = {}
t.x = 1
t.y = 2

t.x = t.x + 2

for k, v in pairs(t) do
  print(k, v) -- will print x 3 \n y 2
end
adds to t two elements, modify one and prints keys and values of each rows.

Q3: How does or affect the variable assigning? in self.controls = options.controls or {up = "up", down = "down", left = "left", right = "right"}, does that mean self.controls becomes both possible values? This is one I'm stumped on
"or" and "and" are used as shortcut to if statements.
The equivalent or the line you quoted is :
Code: [Select]
if not options.controls then
  self.controls = {up = "up",
                        down = "down",
                        left = "left",
                        right = "right"}
else
  self.controls = options.controls
end

Another example :

Code: [Select]
a = 1
b = nil
c = 3

d = c and a or b -- d = 1
d = a and b or c -- d = 3
d = b and a or c -- d = 3


Q4: Also another one, I've never been very confident in what return means (even though I've encountered it in several languages such as JavaScript. I've known it to return a value if it refers to a variable but it seems that elsewhere in the code it can represent some other things too? Clarification?
The main difference between return in Lua and return in Javascript is that in Lua's return, you can return multiple values (known as "tuple")
Code: [Select]
x, y = 42, 69
function getCoords()
  return x, y
end

function setCoords(xx, yy)
  x, y = xx + 1, yy + 1
end

x, y = getCoords()
print(getCoords())  -- prints 42 and 69
setCoords(getCoords())
print(getCoords())  -- prints 43 and 70



Q5: Generally I don't understand classes enough, I don't think I finished reading through the inspired lua tutorial though. Might go back and read it ;D
Classes in Lua are based on metatables that can be a nightmare if you don't understand their concept. Maybe you can read for that.
If you still don't understand metatable (I was not able to understand them at the beginning, but understood classes) think of classes in other languages.
The main difference is that you don't have virtual method walkthrough since when you inherit from another class all the references are copied and the one you override overrides the references in the metatable losing the reference to the parent class. The only way to use a parent class is either by modifying the class() function, or by knowning the name of the parent class and using Parent.method(child, args) bootstraping the ":" notation.
Title: Re: Lua Q&A
Post by: Jonius7 on July 22, 2013, 09:25:44 pm
I had a response to this, but I lost it when I reloaded the page.
One thing: no wonder the class syntax is screwing me over. I'll have to try and slowly understand every line...
Code: [Select]
Foo = class()
function Foo:init()
  self.i = 69
end
function Foo:bar(i)
  print(i, self.i)
  self.i = i
end
foo = Foo()
foo:bar(42) -- calls Foo.bar(foo, 42) ; prints 42 69
foo:bar(42) -- prints 42 42
print(Foo.i)  -- nil
Foo:bar(42) -- calls Foo:bar(Foo, 42) ; prints 42 nil
print(Foo.i) -- prints 42
Title: Re: Lua Q&A
Post by: Levak on July 22, 2013, 09:38:39 pm
I Edited my post :

Code: [Select]
-- Foo:bar(42) -- calls Foo:bar(Foo, 42) ; prints 42 nil
++ Foo:bar(42) -- calls Foo.bar(Foo, 42) ; prints 42 nil

I thought I had fixed it before but in fact, it somehow returned to the old version :p
Title: Re: Lua Q&A
Post by: Jonius7 on July 26, 2013, 12:43:42 am
Code: [Select]
Foo = class()
function Foo:init()
  self.i = 69
end
function Foo:bar(i)
  print(i, self.i)
  self.i = i
end
foo = Foo()
foo:bar(42) -- calls Foo.bar(foo, 42) ; prints 42 69
foo:bar(42) -- prints 42 42
print(Foo.i)  -- nil
Foo:bar(42) -- calls Foo.bar(Foo, 42) ; prints 42 nil
print(Foo.i) -- prints 42
This is too confusing. All the cross-referencing and assigning a var to another var, then using them in combination is obscuring the meaning for me. I rarely like to do this in my own programming.
Code: [Select]
foo = Foo()
Is this really needed?

Code: [Select]
foo:bar(42) == Foo():bar(42) -- that makes some sense now, does it call upon Foo() first, then Foo:bar(i) ? doesn't seem right
foo:bar(42) -- so the second time, because of self.i = i from the first time around, self.i == i
print(Foo.i) -- why is this nil? Is it because Foo:bar(i) took over the 'control' of self.i so Foo:init() doesn't control it anymore
Foo:bar(42)
print(Foo.i)

Now, you lost me.




EDIT:
Q2: What does . refer to? From what I gather it would mean it would add it to a list/table so that if Coyote was called up, you'd get Coyote == {"x"==x, "y"==y, "tiles"=={} etc...}. Is this right?
Basic : classes in Lua are reprensented as tables.
"." let you access to one element (defined of not) of a table. In Lua tables are associatives using all sort of hash key (you can use functions or tables as hash key). In general you access an element using its key with [ and ] such as :
Code: [Select]
t = {foo=bar1, ["foo with spaces"]=bar2}
t["foo"] -- bar1
t["foo with spaces"] -- bar2
t.foo -- bar1
As you can see, since "foo" is a valid identifier, it can be used with the "." convention.
What do you mean by a valid identifier? Does that mean with no spaces? Or does it cover something else as well?
Title: Re: Lua Q&A
Post by: Levak on July 26, 2013, 03:47:02 am
Code: [Select]
foo = Foo()
Is this really needed?
If you're asking this question, you may not know that Lua is case sensitive.
Here, Foo is the class (or the "template to copy") and foo is the new object (or an "instance of this class").
Foo() is equivalent to "new Foo()" in some other POO languages.
Foo() calls Foo:init().

Quote
Q2: What does . refer to? From what I gather it would mean it would add it to a list/table so that if Coyote was called up, you'd get Coyote == {"x"==x, "y"==y, "tiles"=={} etc...}. Is this right?
Basic : classes in Lua are reprensented as tables.
"." let you access to one element (defined of not) of a table. In Lua tables are associatives using all sort of hash key (you can use functions or tables as hash key). In general you access an element using its key with [ and ] such as :
Code: [Select]
t = {foo=bar1, ["foo with spaces"]=bar2}
t["foo"] -- bar1
t["foo with spaces"] -- bar2
t.foo -- bar1
As you can see, since "foo" is a valid identifier, it can be used with the "." convention.
What do you mean by a valid identifier? Does that mean with no spaces? Or does it cover something else as well?
A valid identifier is basically a name you would give to a variable.
"foo_bar" is valid, "foo-bar" is not", "foo bar" is not, "foo/bar" is not, etc ...
Title: Re: Lua Q&A
Post by: Jim Bauwens on July 26, 2013, 08:04:41 am
Well, here is an other example, hope it's a bit more clear.

So, lets say you have a car driving game and all the cars should have their own set of attributes. Managing this using classes is very easy, you start by creating your Car class, basically a prototype of your car or if said in another way, the mold you use to create all your cars.

Code: [Select]
Car = class()
function Car:init(model)
  self.model = model or "LuaCar"
  self.distance = 0
end

function Car:drive(d)
  self.distance = self.distance + d
  print(self.model .. " just drove " .. d .. " km")
end

function Car:totalDistance()
  print(self.model .. " drove " .. self.distance .. " km in total")
end

So, that's our class. Now a Car has two properties, a model name and a distance. Now lets make some Car objects and play with them.

Code: [Select]
myCar1 = Car("Fiat Ducato")
myCar2 = Car("Ford Fiesta")

myCar1:totalDistance()
myCar2:totalDistance()

print()

myCar1:drive(10)
myCar2:drive(5)

print()

myCar1:totalDistance()
myCar2:totalDistance()

print()

myCar2:drive(10)

print()

myCar1:totalDistance()
myCar2:totalDistance()

the output of this is

Code: [Select]
Fiat Ducato drove 0 km in total
Ford Fiesta drove 0 km in total

Fiat Ducato just drove 10 km
Ford Fiesta just drove 5 km

Fiat Ducato drove 10 km in total
Ford Fiesta drove 5 km in total

Ford Fiesta just drove 10 km

Fiat Ducato drove 10 km in total
Ford Fiesta drove 15 km in total

As you can see, myCar1 and myCar2 are total different instances (objects) of Car. You can use all the methods defined in the Car class. The 'self' refers to each unique instance.

As Levak said, the ':' isn't actually more than a short cut. Take for example the Car:drive method. You could also write it this way and it would work exactly the same:
Code: [Select]
function Car.drive(self, d)
  self.distance = self.distance + d
  print(self.model .. " just drove " .. d .. " km")
end

Now, if we call myCar1:drive(10), that would be the same as myCar1.drive(myCar1, 10). Through metatables the myCar1 table is linked to the Car table (object and classes are in the end still tables). So basically when you do myCar:drive(10) you do Car.drive(myCar1, 10).
Title: Re: Lua Q&A
Post by: mannuri on July 26, 2013, 04:25:22 pm
Hi, Im triing make a program that need solve complex stuff, and i need to use nsolve( or solve( function since is for cas version.

here is my code:
Quote
cvi=cvi*10^(-7)
    ui=(qi*4)/(math.pi*di*di)
    rei=tostring((ui*di)/(cvi))
    di=tostring(di)
    ki=tostring(ki)
 
    formula = "yi^(−0.5)=−2*log(((ki)/(di*3.7))+((2.51*yi^(−0.5))/(rei)),10)"

    var.store("formula", formula)
    equacao = "string(nSolve(expr(formula), yi)|yi<0.1 and yi>0"
    yi = math.eval(equacao)

When i go display, i got error.
Quote
attempt to concatenate global 'yi' (a nil value)

I have trie:
Quote
--whitout var.store("formula", formula)
equacao = "nSolve(formula, yi)|yi<0.1 and yi>0"

Please help me. thanks!
Title: Re: Lua Q&A
Post by: jwalker on July 26, 2013, 04:38:37 pm
Hi, Im triing make a program that need solve complex stuff, and i need to use nsolve( or solve( function since is for cas version.

here is my code:
Quote
cvi=cvi*10^(-7)
    ui=(qi*4)/(math.pi*di*di)
    rei=tostring((ui*di)/(cvi))
    di=tostring(di)
    ki=tostring(ki)
 
    formula = "yi^(−0.5)=−2*log(((ki)/(di*3.7))+((2.51*yi^(−0.5))/(rei)),10)"

    var.store("formula", formula)
    equacao = "string(nSolve(expr(formula), yi)|yi<0.1 and yi>0"
    yi = math.eval(equacao)

When i go display, i got error.
Quote
attempt to concatenate global 'yi' (a nil value)

I have trie:
Quote
--whitout var.store("formula", formula)
equacao = "nSolve(formula, yi)|yi<0.1 and yi>0"

Please help me. thanks!

You never set a value to or declared yi before in your program, thus it has no value and is considered nil.
Title: Re: Lua Q&A
Post by: mannuri on July 27, 2013, 05:27:17 am
Thanks!

I used the script:
Quote
rei=tostring((ui*di)/(cvi))
    di=tostring(di)
    ki=tostring(ki)
    yi="0.01"
    formula="yi^(−0.5)=−2*log(((ki)/(di*3.7))+((2.51*yi^(−0.5))/(rei)),10)"
    yi="nSolve("..formula.."),yi)"

and i got the output display:
Quote
yi=nSolve(yi^(−0.5)=−2*log(((ki)/(di*3.7))+((2.51*yi^(−0.5))/(rei)),10)),yi)
All is going good :)

but when i change the code to:
Quote
yi=math.eval("nSolve("..formula.."),yi)")
yi got nil value :(
Title: Re: Lua Q&A
Post by: Adriweb on July 27, 2013, 06:24:35 am
Not sure why this wouldn't work, but you can try storing temporarily the left and right side of the equation into a basic variable (with some other simpler math.eval("left:=xxxxx") etc.)
and then, math.eval("nSolve(left=right,yi)")

Edit : thanks to jim : indeed you have a ")" after the formula that will break everything :P remove it !
Title: Re: Lua Q&A
Post by: mannuri on July 28, 2013, 07:57:23 am
thanks, but still got the same error.
Im using the ti cas teacher edition to edit and run the script. lastest version.
im using the TI Master Box Tool.
Quote
function Tipo1:Save()
    --Turn string into number--
    qi=math.eval(numberBoxQ.text)
    li=math.eval(numberBoxL.text)
    di=math.eval(numberBoxD.text)
    cvi=math.eval(numberBoxcv.text)
    ki=math.eval(numberBoxK.text)
    --If no imput variable get 0--
    if numberBoxQ.text == "" then
    qi=0
    end
    if numberBoxL.text == "" then
    li=0
    end
    if numberBoxD.text == "" then
    di=0
    end
    if numberBoxcv.text == "" then
    cvi=0
    end
    if numberBoxK.text == "" then
    ki=0
    end
    --Solving the problem--
    ui=(qi*4)/(math.pi*di*di)
    rei=(ui*di)/(cvi)
    --Using tostring to insert into formula--
    rei=tostring(rei)
    di=tostring(di)
    ki=tostring(ki)
    --Declaring yi close value from the real expected--
    yi="0.01"
    --full formula--
    math.eval("yi^(−0.5)=:fl")
    math.eval("−2*log(((ki)/(di*3.7))+((2.51*yi^(−0.5))/(rei)),10)=:fr")
    --solving the formula--
    yi=math.eval("nSolve(fl=fr,yi)")
    --disp results--
    helpLaunch(Resultados1)
end
    --simple round--
function round(num, idp)
  local mult = 10^(idp or 0)
  return math.floor(num * mult + 0.5) / mult
end

Resultados1 = class()

function Resultados1:init()
   
    labelBoxu = LabelBox("          U = "..round(ui,7).." m/s")
    labelBoxre = LabelBox("          Re = "..round(rei,7))
    --Got problem here--171: attempt to concatenate global 'yi' (a nil value)--
    labelBoxy = LabelBox("          λ = "..yi)

I have trie sneack into formula pro lua code, but i dont understand how the solve works there  <_<
maybe if the nsolver dont disp only 1 awsner yi got nil? how i solve it?

Sorry for the big post.
edit:change left and right to fl and fr, because left() is a nspire function. still got yi nil value

edit 2:
FINNALY!!!, i made it!
i just need var.store() all vars and its done.

Thank you guys i love you all!!
Title: Re: Lua Q&A
Post by: Jonius7 on July 28, 2013, 08:09:20 pm
Code: [Select]
foo = Foo()
Is this really needed?
If you're asking this question, you may not know that Lua is case sensitive.
Here, Foo is the class (or the "template to copy") and foo is the new object (or an "instance of this class").
Foo() is equivalent to "new Foo()" in some other POO languages.
Foo() calls Foo:init().

[/quote]

I am aware that Lua is case sensitive, but can Foo() just be used directly in conjunction with . and :

eg:
Code: [Select]
Foo():bar(42)Actually I'm not sure that looks valid...

@Jim Bauwens: I think I'm starting to get the interaction between : and . now.
Title: Re: Lua Q&A
Post by: Levak on July 28, 2013, 08:45:09 pm
I am aware that Lua is case sensitive, but can Foo() just be used directly in conjunction with . and :

eg:
Code: [Select]
Foo():bar(42)Actually I'm not sure that looks valid...
It is valid, but keep in mind that it will create a new instance every time you use that.
It can be useful in certain specific cases, but not in general.
Title: Re: Lua Q&A
Post by: Jonius7 on July 29, 2013, 01:18:44 am
Actually, looking at it again,  I think I get it now more,

when you do foo = Foo(), that's similar to something like ball = Class() right?
It clicked for me when you said that Foo() was the class, and foo became the object.

About creating new instances with Foo():bar(42),
does that have any other disadvantages, such as some sort of memory leak?
Title: Re: Lua Q&A
Post by: Levak on July 29, 2013, 01:33:58 am
when you do foo = Foo(), that's similar to something like ball = Class() right?
It clicked for me when you said that Foo() was the class, and foo became the object.
Yes.
It is equivalent to ball = new Class() in other POO languages.

Quote
About creating new instances with Foo():bar(42),
does that have any other disadvantages, such as some sort of memory leak?
Only Memory Leaks (and maybe stupid beginner errors like "why my code doz not work" just because your creating a new object each time that has its own properties).
Title: Re: Lua Q&A
Post by: Jonius7 on July 29, 2013, 08:45:42 am
Quote from: mannuri
edit 2:
FINNALY!!!, i made it!
i just need var.store() all vars and its done.

Thank you guys i love you all!!
so var.store() solves the problem?
I wonder how it does that...


Code: [Select]
yi=math.eval("nSolve(fl=fr,yi)")
I was thinking this line might not work, but on second thought, it looks all right.


Also more questions
Also in my previous post, I made a mistake, class shouldn't be capitalised, should all be lower case, so that was wrong.
So clarification,

Code: [Select]
ball = class() -- creates a class called ball using the class function that is predefined
function ball:init(speed, size) -- initialises the class, it can be called by just ball() elsewhere in the code
   self.speed = spd -- these are added to the table, ball?
   self.size = size
end
Title: Re: Lua Q&A
Post by: Adriweb on July 29, 2013, 10:17:54 am
So clarification,

Code: [Select]
ball = class() -- creates a class called ball using the class function that is predefined
function ball:init(speed, size) -- initialises the class, it can be called by just ball() elsewhere in the code
   self.speed = spd -- these are added to the table, ball?
   self.size = size
end
Yes (and it's 'speed' not 'spd').

However, it's a general habit that classes definitions are first-letter-capitalized :
Ball = class()
function Ball:init(arg1, arg2) ... end

etc.

and instances of the classes, first-letter-lowercase :

myBall = Ball(5,10)
Title: Re: Lua Q&A
Post by: mannuri on July 29, 2013, 10:39:43 am
var.store() and math.eval() for me is like you put all out of lua and solve as a basic ti language, and take it back to lua.
Title: Re: Lua Q&A
Post by: Jonius7 on July 29, 2013, 06:28:24 pm
Code: [Select]
Ball = class()
Yeah I meant that as well, I forgot about that capitalised in that post. I already had these conventions in my current Lua project. Oops.

Also with instances of the classes, what if you want many instances using the same class,like at least 10? I've thought about using a table/list/array. Then I could call them by just referencing a particular value within the table.
Eg, using the function Ball:init(arg1, arg2)
Like this?
Code: [Select]
ballarray = {{3,4},{6,10},{4,11}...}


Code: [Select]
self.speed = spd
So this is not valid? does it have to be self.speed = speed, or self.speed = 0[a number], or self.speed = {}
EDIT: Oh I see the self.speed has to match the arguments.

function ball:init(speed, size)
   self.speed = speed
   self.size = size

I thought assigning any variable with a valid name would do ok...

Also thanks mannuri for explaining var.store() and math.eval()
Title: Re: Lua Q&A
Post by: Levak on July 29, 2013, 07:15:57 pm
Understand this, you'll understand everything :

Declarations :
Code: [Select]
PointClass = class()
function PointClass:init(x, y)
  self.x = x
  self.y = y
end

BallClass = class(PointClass)
function BallClass:init(x, y, radius)
  PointClass.init(self, x, y)
  self.radius = radius
end

function BallClass:paint(gc)
  gc:fillArc(self.x, self.y, self.radius*2, self.radius*2, 0, 360)
end

Usage :
Code: [Select]
local ball1, ball2
ball1 = BallClass(0, 0, 10)
ball2 = BallClass(50, 50, 15)
ball_tbl = {ball1, ball2}

function on.paint(gc)
  for _, ball in ipairs(ball_tbl) do
    ball:paint(gc)
  end
end
Title: Re: Lua Q&A
Post by: Jonius7 on July 30, 2013, 08:44:06 am
Code: [Select]
PointClass.init(self, x, y)

What does the first argument (self) represent in relation to PointClass?
as compared to
Code: [Select]
PointClass:init(x, y)

Code: [Select]
for _, ball in ipairs(ball_tbl) do
I'm not 100% what in ipairs means as I've never had to use it. Also what does for _ mean? I'm more used to something like for x=sample, sample+9 do.

I know I'm getting closer to understanding everything...
Title: Re: Lua Q&A
Post by: ElementCoder on July 30, 2013, 08:52:58 am
ipairs will iterate over the pairs (1, ball[1]), (2, ball[2], ..., (n, ball[n]) till there is no 'n' anymore.
The underscore is just a variable like a,b,c,d etc. but used when you don't care about the variable. Say you were only interested in the values, you'd do
Code: [Select]
for _, values in ipairs(ball_tbl) do
 --Do something here
end
AFAIK it's just a style recommendation to indicate you ignore that variable.
Title: Re: Lua Q&A
Post by: Adriweb on July 30, 2013, 09:16:45 am
Code: [Select]
PointClass.init(self, x, y)
What does the first argument (self) represent in relation to PointClass?
as compared to
Code: [Select]
PointClass:init(x, y)
Well, this wouldn't work. (the ":" would mean that the PointClass table (class definition !) is passed.)

For the first line of code you quoted, "self", there, is from the BallClass, not the PointClass. He's using PointClass.init (and not :init) because he specifies the object to be used for instanciation : the current (ball) self. As said before, ":" is just a shortcut for a.b(self)


Also, for pairs/ipairs : look here http://lua-users.org/wiki/ForTutorial
Title: Re: Lua Q&A
Post by: Jonius7 on July 31, 2013, 07:52:10 am
Ah, I'm making stupid mistakes again, I go back and look at it again and see that that line is within the function BallClass:init(x, y, radius)

Oh of course, I get what ipairs is now. Takes all the indices in numbered order (ones that can be ordered anyway), and has the indicies and keys from the table in pairs. Ok.

Oh wow I didn't know that _ could be used as a variable. Kinda like a wild card. Is it?
Spoiler For This question isn't so important, the more pressing stuff is below:
so can _ be used mixed like how you would search using * in other languages
Eg: you have variables bark, bork, berk
can you look for b_rk somehow?

Quote
":" is just a shortcut for a.b(self)
So PointClass:init(x, y) is a shortcut for PointClass.init(PointClass, x, y)
How does that translate to something in a table?

I'm trying to work through in my mind the connections between all this stuff, and I still don't quite get it. I even drew a diagram, draft version, probably some mistake in there ;).
To describe what i'm not getting, it's the syntax that's getting me. I'm having trouble understanding the meaning of certain parts of the syntax lua classes use.
Title: Re: Lua Q&A
Post by: Levak on July 31, 2013, 02:18:08 pm
Ah, I'm making stupid mistakes again, I go back and look at it again and see that that line is within the function BallClass:init(x, y, radius)

Oh of course, I get what ipairs is now. Takes all the indices in numbered order (ones that can be ordered anyway), and has the indicies and keys from the table in pairs. Ok.

Oh wow I didn't know that _ could be used as a variable. Kinda like a wild card. Is it?
Spoiler For This question isn't so important, the more pressing stuff is below:
so can _ be used mixed like how you would search using * in other languages
Eg: you have variables bark, bork, berk
can you look for b_rk somehow?

No, "_" is just a valid char as a variable name such as _a, _foo, ________bar, foo_bar or even _ or _____, etc ...
Futhermore, "_" is in the Lua's culture (same in OCaml for example) a junk variable. It is then used when you know you don't want to use it.
But this doesn't mean it has a special meaning for the Lua's interpretor, for example this works :
Code: [Select]
local _o = 42
for _=1, _o do
 print(_, _+1, _o/_)
end


Quote
Quote
":" is just a shortcut for a.b(self)
So PointClass:init(x, y) is a shortcut for PointClass.init(PointClass, x, y)

I'm trying to work through in my mind the connections between all this stuff, and I still don't quite get it. I even drew a diagram, draft version, probably some mistake in there ;).
To describe what i'm not getting, it's the syntax that's getting me. I'm having trouble understanding the meaning of certain parts of the syntax lua classes use.

Yes ":" is a shortcut to "." + self, you understood that well.
Where you're going "too far" in the understanding is that you substitude "self" as the ClassName which is not always the case.
"self" is a dynamic variable, its meaning is determined at running time. Just remind that "self" refers to the first argument when using the ":" notation.
For example, these 3 calls are differents :
Code: [Select]
Toto = class()
function Toto:init()
  print(self)
end

Toto:init()     -- equivalent to Toto.init(Toto)
lol = Toto()   -- equivalent to Toto.init(temp) where "temp" will be stored in "lol"
lal = lol.init({}) -- here we force "self" to be "{}", an empty table


Quote
How does that translate to something in a table?

This is an intersting deep question. Jim will maybe better explain than me, but I'll try something :
In Lua, table have a "prototype" table that describe their content and how to access an element. This inner table is called "metatable".
You can get/set the metatables using getmetatable(tbl) or setmetatable(tbl, meta).
There are special elements (http://lua-users.org/wiki/MetamethodsTutorial) of the metatable that changes the meaning of tbl[a] for example, or t1 + t2. It's like operator overloading.

Metatables in classes are used to transfert all the links to the functions from the "template" (the class) to the "instance" (the object) without copying them.
This means that when you're doing foo = Foo(), you end up with a new table (foo) that has the metatable of Foo (the class) that refers to every single function you defined in Foo (Foo.bar() for example).
Using the same principle, when doing Bar = class(Foo), you end up with a new table (Bar) that has the metatable of Foo (the parent class) that refers to every single function you defined in Foo. What's the difference then ? Foo() will also call Foo:init() after the copy (the constructor).
Title: Re: Lua Q&A
Post by: Jonius7 on August 01, 2013, 09:24:37 am
Ah thank you, this helps. Thanks for the help in explaining self, my head is still flipping from the uses of . and : but now I've understood the concepts, the stuff previously said makes more sense now.

Code: [Select]
Bar = class(Foo)
So this will also call Foo:init() after it assigns the table of Bar? That's interesting.
Title: Re: Lua Q&A
Post by: Levak on August 01, 2013, 11:59:02 am
Code: [Select]
Bar = class(Foo)
So this will also call Foo:init() after it assigns the table of Bar? That's interesting.
No, this is not what I've written :

Quote
What's the difference then ? Foo() will call Foo:init() after the copy (the constructor).

class() does not call init().
Title: Re: Lua Q&A
Post by: Adriweb on August 02, 2013, 12:17:26 pm
If you want to know what's behind the scene, the source code of the "class" function implementation is here : http://wiki.inspired-lua.org/class
Title: Re: Lua Q&A
Post by: Jonius7 on August 04, 2013, 09:53:03 am
@adriweb: Yeah I've seen it, I understand the actual definition even less. Sorry.
http://ourl.ca/11717/354363

@Levak: Yeah I don't know what I was going on back there.  We were looking at
foo = Foo()
and
Bar = class(Foo)
Title: Re: Lua Q&A
Post by: Adriweb on August 04, 2013, 01:00:19 pm
@adriweb: Yeah I've seen it, I understand the actual definition even less. Sorry.
Oops yeah sorry, didn't see/remember.
But indeed it's not a trivial code for novice programmers.

and to sum up the init() call, class() does not call it, it's when you create an instance of the earlier-defined class that it's called.
Title: Re: Lua Q&A
Post by: Jonius7 on August 04, 2013, 10:17:05 pm
EDIT: I changed some things because I changed my understanding...
So clarification,

Code: [Select]
ball = class() -- creates a class called ball using the class function that is predefined
function ball:init(speed, size) -- initialises the class, it can be called by just ball() elsewhere in the code
   self.speed = spd -- these are added to the table, ball?
   self.size = size
end
Yes (and it's 'speed' not 'spd').

I am so confused, which parts in initialising self.blah variables have to match the arguments? In this case, speed and size? I thought only the blah part in self.blah had to match the arguments.

I thought there was no restrictions, i.e. doing this wouldn't give any errors when executing the code.


Taking some code from my (currently) secret project

Code: [Select]
function Units:init(plr, x, y, str, move, opt) -- player, xy position on map, strength, movement, options
self.plr = uplr
self.x = ux
self.y = uy
self.str = ustr
self.move = umove
self.opt = {}
end
Is this valid at all? EDIT OVERRIDE: No, it is not valid code. I think because uplr, ux, uy aren't defined? Hence self.plr, self.x sel.y ... are assigned values of nil. That's why I'm not getting an error, even when calling the function. It's only when I tested trying to gc:drawstring() ustr that it got a nil error.

So if I just change it to

Code: [Select]
function Units:init(plr, x, y, str, move, opt) -- player, xy position on map, strength, movement, options
self.ran = plr
self.dom = x
self.hah = y
self.yea = str
self.ble = move
self.see = {}
        self.new = 10
end
That would be valid, except I probably wouldn't name those self. variable like that, of course

I'm still not sure what all these things do. And what would be the output if I were to call Units and/or Units() ?

I'm also using this to get my head around it as well: http://ourl.ca/12291/231625

As said on my custom title: whyda slow progress in programming? Imma struggle beyond basic concepts...
Title: Re: Lua Q&A
Post by: jwalker on August 04, 2013, 10:44:07 pm
Your origional code would work except when you look at your constructor, your parameters must be equil to your variable.



ex:
Code: [Select]
function Units:init(plr, x, y, str, move, opt) --these are not your self. variables, they are just values that are passed when it is called.
  self.plr = plr --Notice how you are setting the self. variable to the variable passed in the constructor.
  self.x = x
  self.y = y
  self.str = str
  self.move = move
  self.opt = opt
end

When you used uplr instead of the plr you passed in your constructor, you essentialy are setting self.plr to nil because uplr does not exist.
Title: Re: Lua Q&A
Post by: Jonius7 on August 04, 2013, 10:49:42 pm
Yep I edited my posts and talked about the uplr, because uplr hasn't been defined yet.
I edited my post several times, so I may have started to answer my own questions :D

Quote
your parameters must be equil to your variable.
as in? The arguments in the function?
Title: Re: Lua Q&A
Post by: jwalker on August 04, 2013, 10:54:40 pm
Yes, as in arguments.
Title: Re: Lua Q&A
Post by: Levak on August 05, 2013, 01:54:36 am
I really don't understand why you're struggling with scoped-variables-overriding.

What I mean :
Code: [Select]
local foo = 42
{ -- new scope, it can a function, for, while, etc ..
    local foo = 69
    print(foo) -- prints 69
}
print(foo) -- prints 42
Is that a new concept for you ?

Because here, "self" is the object itself, it won't colide with current scope variables.

Thus, this is valid :
Code: [Select]
Foo = class()
function Foo:init(x, y, z)
  self.x = x
  self.y = y
  self.z = z
end

And this is invalid :
Code: [Select]
Foo = class()
function Foo:init(xx, yy, zz)
  x = xx
  y = yy
  z = zz
end


But obviously, this is also valid :
Code: [Select]
Foo = class()
function Foo:init(xx, yy, zz)
  self.x = xx
  self.y = yy
  self.z = zz
end
Title: Re: Lua Q&A
Post by: Jonius7 on August 05, 2013, 10:32:46 am
I'm probably just thinking things differently to how others might have got the concept in Lua.
I'm not familiar with the word scope (though I searched it up and that helped)
Spoiler For from lua-users.org:
The place where a variable is visible is called the "scope" of a variable.
But using local variables isn't exactly new for me.

The main thing that was stumping me the most was trying to understand what all this syntax that I wasn't familiar with, was doing.
Title: Re: Lua Q&A
Post by: njaddison on February 15, 2014, 12:20:15 am
wheneva i lookz at someone'z lua source code it haz a bunch of trigz and I'z juz like omgz what the crudz doez all this meanz it'z so weirdz
No spamming/trolling intended, I just want to know why you'd wanna use trig in a lua code. I'm not very skilled at programming (YET). Someday, I wanna be the very best. That no one ever was. But anyways, no spamming/trolling intended.
Title: Re: Lua Q&A
Post by: LDStudios on February 15, 2014, 07:17:39 am
Well, I'm assuming you're talking about trigonometry?
I once started (never finished) a game in which the player moves with 2 arrows, controlling a line, that curves, sort of like snake, but not tied to a grid. I used sine and cosine to move the snakes destination point around a circle when the arrows were pressed. Thats one example.
Title: Re: Lua Q&A
Post by: njaddison on February 15, 2014, 09:15:16 am
Yes I'm guessing that trigonometry is essential if I want to learn to program games. I learned basic trig in Geometry, how can I apply that to programming? It's something I've been wondering for a very long time, as i want to program my first game in lua, on the nspire.
EDIT:
Not actually ON the nspire, just for it.
Title: Re: Re: Lua Q&A
Post by: DJ Omnimaga on February 15, 2014, 10:12:40 am
Isn't some trig necessary for 3D too?
Title: Re: Lua Q&A
Post by: Hayleia on February 15, 2014, 10:59:53 am
Trig is necessary for everything that involves rotation or turning.
Title: Re: Lua Q&A
Post by: LDStudios on February 15, 2014, 11:18:32 am
Yes I'm guessing that trigonometry is essential if I want to learn to program games. I learned basic trig in Geometry, how can I apply that to programming? It's something I've been wondering for a very long time, as i want to program my first game in lua, on the nspire.
EDIT:
Not actually ON the nspire, just for it.

Trig isnt really essential, unless you are going to work with rotating around a fixed point, or I guess if you are making some sort of 3D environment like DJ Omnimaga said
Title: Re: Lua Q&A
Post by: njaddison on February 15, 2014, 09:24:12 pm
OK, so I'm programming my first game in Nspire Lua, and I have a lot of questions, but first let me deal with problems I've had so far.
The game is a simple pong clone. Here is the code so far:
Code: [Select]
function on.paint(gc)
    local screen = platform.window
    local h=screen:height()
    local w=screen:width()
    gc:setFont("sansserif", "b", 24)
    gc:setColorRGB(255,193,37)
    local sw = gc:getStringWidth("Pong")
    local sh = gc:getStringHeight("Pong")
    gc:drawString("Pong",w/2-sw/2,h/16+sh/16)
    gc:setFont("sansserif", "r", 12)
    gc:setColorRGB(255,255,255)
    local s2w = gc:getStringWidth("Simple Pong clone by njaddison")
    local s2h = gc:getStringHeight("Simple Pong clone by njaddison")
    gc:drawString("Simple Pong clone by njaddison",w/2-s2w/2,h/2+s2h/2)
end

function on.enterKey()
    screen:invalidate()
end
So far I've finished the title screen (subject to change) and that's pretty much it. I'm trying to make it so once you press the escape key after the game starts (game starts by pressing enter key), it will restart the code, or at least recall the title screen function. I think this is possible with
Code: [Select]
while true do loop, but I kept running into errors, and I don't even know if I can recall a function that is in a loop with a function that is outside of one.
Also, how would I go about making the title screen background black? I want it to look a bit like the original pong, and also, you can't see the "Simple pong clone by njaddison" if the screen is white because the text is white.

EDIT:
Also, an animation of pong in the background of the title screen would be nice, like with the lua clone of Cubefield.
Title: Re: Lua Q&A
Post by: LDStudios on February 15, 2014, 09:44:07 pm
Well, I'm not really an expert, but here are some things:
You can use on.activate() so that every time u open it up it returns to the title screen. In on.activate, i would call a function to reset it to the title screen, and you can call the same function in your on.escapeKey() function.

To make the screen black:

gc:setColorRGB(0,0,0)
gc:fillRect(0,0,w,h)
Title: Mirroring Images?
Post by: LD_Chimpman on March 20, 2014, 10:43:47 pm
Hi, I wanted to know how to go about mirroring an image locally in lua. I have a bunch of images for character animations and I need copies of them mirrored horizontally but instead of inserting them in as seperate mirrored images I'd like to make mirrored copies of them within my code.

The first thing I tried was using image:copy() to copy them and make the width negative, however that gave an error since lua requires the width value to be >0.

Next I studied the way the image strings are made and figured out how I could potentially switch certain parts of an image's string to mirror it. However, I tried to make a function that would manipulate parts of an image's string and got errors, because the foreward slash that is used in the strings doesn't function like a normal string value, and it overally screws up everything you try to do with it (I tried using "\\" too, but then it didn't think that "\" in the image string = "\\").

So before I go crazy searching further for a really complex way to manipulate image strings, is there a simpler way to mirror images in lua?
Please help!  ???
Title: Re: Lua Q&A
Post by: Jonius7 on March 26, 2014, 06:30:57 pm
I'm not so sure about mirroring images within the Lua code itself, but if you have the original image (.gif, .png etc) you could mirror it and convert it to image code.
Title: Re: Lua Q&A
Post by: LD_Chimpman on March 26, 2014, 09:26:58 pm

I'm not so sure about mirroring images within the Lua code itself, but if you have the original image (.gif, .png etc) you could mirror it and convert it to image code.

I'm hoping that I won't have to do that. I have quite a few images because they are for animations, and duplicating every one of those images to have a mirrored version of it would almost double the current file size. I know it has to be possible to do it locally since nspaint can modify and output image code, I'm just not quite sure how.
Title: Re: Lua Q&A
Post by: Jim Bauwens on March 27, 2014, 06:08:20 pm
Take a look at http://wiki.inspired-lua.org/TI.Image (http://wiki.inspired-lua.org/TI.Image). At the moment I don't have time to write a routine, but if you spend some time reading how the format works you should be able to do it. :)


Edit:
Whatever:
Code: [Select]

function mirror_img(imgstr, width , height)
    local out = imgstr:sub(1, 20)
    local p = 21
    for y=1, height do
        local row = ""
        for x=1, width do
        row =  imgstr:sub(p, p +1) .. row
        p = p + 2
    end
    out = out .. row
  end


  return out
end


img_hi_src = "\32\0\0\0\32\0\0\0\0\0\0\0\64\0\0\0\16\0\1\000alalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalal\194\253alalalalalalalalalalalalalalalalalalalalalalalalalalalalalalal\194\253alalalalalalalalal\194\253alalalalal\194\253alalalalal\194\253\194\253alalalalalalal\194\253\194\253alalalalalalalalal\194\253alalalalal\194\253alalalalal\194\253\194\253alalalalalalal\194\253\194\253alalalalalalalalal\194\253alalalalal\194\253alalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalal\194\253alalalalalalalalalalalalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalal\194\253alalalalalalalalalalalalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalal\194\253alalalalalalalalalalalalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalal\194\253alalalalalalalalalalalalalal\194\253\194\253alalalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalalalal\194\253\194\253\194\253\194\253\194\253\194\253\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalal\194\253\194\253\194\253\194\253\194\253\194\253alal\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalal\194\253\194\253\194\253alal\194\253\194\253\194\253\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalalal\194\253\194\253alalalalal\194\253alalalalalalalalalalalalalal\194\253alalalalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253alalalalalalalalal\194\253a\144alalalalal\194\253alalalalalal\194\253alalalalalalalalalalalalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalalalal\194\253alalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalalal\194\253\194\253alalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253\194\253\194\253alalalalalalal\194\253\194\253alalalalal\194\253alalalalalal\194\253alalalalalalal\194\253\194\253alalalalalalalalal\194\253alalalalalalalalalalalalalalalalalalalal\194\253alalalalalalalalalal\194\253alalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalal"


img_hi = image.new(img_hi_src)
img_hi_reverted=image.new(mirror_img(img_hi_src, 32, 32))


function on.paint(gc)
    gc:drawImage(img_hi, 10, 10)
    gc:drawImage(img_hi_reverted, 10, 100)
end
Title: Re: Lua Q&A
Post by: LD_Chimpman on March 27, 2014, 07:02:21 pm
Thanks so much!

I actually had spent some time studying the lua image string format by loading in a 2x2 pattern as well as a mirrored copy of the image and I found what parts of it
I needed to move around, my problem was the implementation of it. I was trying to split the image string into table values, separated by each "\". Then I was going
to move around the table values and concatenate the table for the final mirrored image. However since forward slashes act as some kind of weird special character
in lua, it overall just didn't work. I guess I was over complicating it.


Thanks again, now I can continue to make progress on my project!


For your help, here's a teaser (http://0verhyped.files.wordpress.com/2012/05/braid_hourglass.jpg) of my project which so far is turning out really awesome if I do say so myself!  ;D
Title: Re: Lua Q&A
Post by: AnToX98 on March 29, 2014, 02:37:05 am
Guys please Help me !


I can't find how to modify a segment shape position :(


It is actually possible ?


To get the segment coordinates : mysegment:a()/mysegment:b(), but I can't modify them :(
Title: Re: Lua Q&A
Post by: AnToX98 on March 30, 2014, 08:57:28 am
Please could someone help me :( ?
Title: Re: Lua Q&A
Post by: Jim Bauwens on March 30, 2014, 05:06:02 pm
Please could someone help me :( ?

Try calling the setPos function of the body you attached the segment to.
Title: Re: Lua Q&A
Post by: AnToX98 on March 31, 2014, 02:26:19 am
Here's my code :


Code: [Select]
------------------------------------------------
----------- LUA FALLDOWN, BY ANTOX98 -----------
------------------------------------------------


platform.apilevel = "2.0"


require "physics"


----------------------
----- BALL CLASS -----
----------------------


Ball = class()
Seg = class()


function Ball:init(x, y, w, mass)   
    self.width = w
    self.body = physics.Body(mass, physics.misc.momentForCircle(mass, 0, 10, ZERO))
    self.body:setPos(physics.Vect(x, y))
    self.body:setMass(mass)
    self.shape = physics.CircleShape(self.body, w, ZERO)
    self.shape:setRestitution(0.6)
    self.shape:setFriction(0.6)
end


function Seg:init(x1, y1, x2, y2)
    local a, b = physics.Vect(x1, y1), physics.Vect(x2, y2)
       
    local mass = physics.misc.INFINITY()
    self.coor = {x1,y1,x2,y2}
    self.body = physics.Body(mass, physics.misc.momentForSegment(mass, a, b))
    --self.body:setPos(physics.Vect(x1, y1))
    self.body:setMass(mass)
    self.shape = physics.SegmentShape(self.body, a, b, 10)
    self.shape:setRestitution(0.6)
    self.shape:setFriction(0.6)
end


function Ball:paint(gc)
    local p = self.body:pos()
    local x, y = p:x(), p:y()
    local r = self.width / 2
   
    gc:setColorRGB(255,0,0)
    gc:fillArc(x+r, y+r , self.width, self.width, 0, 360)
end


function Seg:paint(gc)
   
    local a = self.shape:a()
    local b = self.shape:b()
   
    gc:setColorRGB(0,0,0)
    gc:drawLine(a:x(), a:y(), b:x(), b:y())
end


function initGame()
    w = 318
    h = 212
   
    ZERO = physics.Vect(0,0)
    LARGE = physics.misc.INFINITY()
   
    space = physics.Space()
    space:setGravity(physics.Vect(0,9.)
   
    sol = Seg(0,200,w,200)
    --space:addBody(sol.body)
    space:addShape(sol.shape)
   
    ball = Ball(w/2-10, 30, 20, 1000)
   
    space:addBody(ball.body)
    space:addShape(ball.shape)
   
    sol.body:setPos(physics.Vect(0,-30))
   
    timer.start(0.01)
end
initGame()


function on.timer()
    space:step(0.1)
    platform.window:invalidate()
end


function on.paint(gc)
    ball:paint(gc) 
    sol:paint(gc)
end

sol.body:setPos(physics.Vect(0,-30))
[/size]
[/size][size=78%]Strangely, the body moves but not the shape....[/size][/code]