Jump to content


Ponder's Content

There have been 49 items by Ponder (Search limited from 10-February 22)


By content type

See this member's


Sort by                Order  

#27222 Lua Table Oddity

Posted by Ponder on 18 August 2012 - 05:12 PM in Ask a Pro

View PostPharap, on 18 August 2012 - 03:40 PM, said:

View PostPonder, on 18 August 2012 - 01:08 PM, said:

If I remember correctly the "==" operator does not check whether the given values evaluate equal, but whether they are the same object in memory.

In the first example you create two different tables even though they have the same content. They have to be stored in different locations in memory, because tables are mutable.
In the second example you only create one table, but have it referenced by two variable name. Hence there is only one table stored in memory and since tab1 and tab2 are pointing to the same chunk of memory they are the same.
That makes no sense though, because if I ran this:
local var1 = 5
local var2 = 5
if var1 == var2 then print("true") else print("false") end
The result would be true, contradicting the way tables are handled.
In almost any other language, the two tables would be declared equivalent.
If lua was going to implement pointing to memory, surely it would make more sense to handle it like C++ and have an operator for it. It's just plain awkward doing it otherwise.

Nope, since integers are immutable, there is no need for the interpreter to create two chunks of memory which hold the same value. In your example both var1 and var2 are pointing to the same location and are therefor equal.
That is if I remember correctly, been some time since I read about it.
I do agree with you however that Lua's behavior is irritating there and there should be something like a "is" operator which does that kind of thing.



#27174 Lua Table Oddity

Posted by Ponder on 18 August 2012 - 01:08 PM in Ask a Pro

If I remember correctly the "==" operator does not check whether the given values evaluate equal, but whether they are the same object in memory.

In the first example you create two different tables even though they have the same content. They have to be stored in different locations in memory, because tables are mutable.
In the second example you only create one table, but have it referenced by two variable name. Hence there is only one table stored in memory and since tab1 and tab2 are pointing to the same chunk of memory they are the same.



#27152 [CC1.5]ComputerCraft Emulator V0.57 (February 19th)

Posted by Ponder on 18 August 2012 - 09:08 AM in APIs and Utilities

Well, meh.
Sorry, that I just assumed that you would give away the code.



#27079 Ignore some results in a subtable.

Posted by Ponder on 18 August 2012 - 12:10 AM in Ask a Pro

That is exactly what you should go for. Have the hands defined by strings and not tables (or just concatenate the tables the moment you check them) and also have some pattern defined as your victory conditions.



#27076 What is you programing / Technical experience ?

Posted by Ponder on 18 August 2012 - 12:02 AM in General

[quote=pharap]
If you rely too heavily on the try statement, you get lazy. If you understand your code, you should be able to make predictions about what errors to expect. And if you find unpredicted errors, you can find out why and thus understand your program better. Besides, if you're using a decent IDE, you don't even need it for debugging since the IDE should tell you about any errors the code encounters through its own debug mode.
When I first started programming, our teacher didn't even teach us about the try-catch statement. I didn't even know it existed until our project was almost over.
[/quote]
Point granted, if you only use try-except to catch everything something is wrong. But if you rely too heavily on your IDE to debug your code... Notice something?

[quote=pharap]
You seem to be forgetting that lua is a basic scripting language. It's not designed for the heavy duty work of languages like Java and the Cs.
Object orientation is very limited and there are only strictly two variable ranges - local and global. Heavy duty languages have public, private, protected, friend, and many other variations or equivalents, as well as fully implemented object orientation, with properties given proper structure and allowing for more advanced methods of encapsulation.
[/quote]
Either I was not clear enough or you are missing my point. My point is not that there are only globals and locals, I am fine with that. It is that locals are not really local, e.g.


[quote name='Paraph]The more you learn your code' date=' the less unforeseen errors you will get.[/quote']
Using try-except does not necessarily mean you don't understand the way your code works. You should only use try-except for specific exceptions anyway. It just makes code more readable.

[quote=Paraph]Every language as its use.[/quote]
And then there is Brain Fuck? Or any other esoteric language for that matter? ;P

Anyway, enough ranting on languages, what was our topic again?



#27056 What is you programing / Technical experience ?

Posted by Ponder on 17 August 2012 - 10:26 PM in General

 nitrogenfingers, on 17 August 2012 - 08:06 AM, said:

Really? Tables are one of my favourite features in Lua. They recognize Lua is a weakly-typed language and that just adds this... flexibility. You can use them to store anything from object-like data, to simple data structs, even commands on behaviours and so much more, all wrapped into this simple, elegant framework. I really think it's one of the strongest features of the language.

 KaoS, on 17 August 2012 - 03:50 PM, said:

I love the lua table system, there is so much more in it and you can do so much more, [...]

I don't see why you should have more flexibility or possibilities with tables. Because tables don't have, as far as I can see (which might not be that far, considering that most of my Lua knowledge was brought to me via google), any new features which distinguishes them from hash tables in other languages. Imo, they're just a mash-up of different container types, which does not seem to actually solve anything.

 Pharap, on 17 August 2012 - 12:29 AM, said:

It's not just python that does classes and the try except, stuff like C# and C++ do it as well. I will admit it is a bit constricting, but the thing is, to catch exceptions, you can usually use if statements to test if something will error before it does. I honestly think that while the try-catch statement comes in handy, it does encourage laziness with some things. Like if you assigned a variable as a byte, to stop it going over the limt (255) you could use a try catch like so: (in C#)
 try {v+=1;} catch {print("error, number has exceeded limit");} 
which is a lazy way of doing:
 if ((v+1) <= 255) {v+=1;} else {print("number cannot go higher, more space must be assigned")} 
So it's not impossible to catch exceptions in lua, you just have to think about it and do it the way they did before the try catch/try except statement: predict possible errors and account for the possibility they might occur.
Yeah, I know that other languages have this too, but I was comparing Python and Lua, should have pointed it out though.
I got to admit that I am a fan of "Crash Early, Crash Often". You cannot possibly think of all errors which might occur and even if you could catching them with if statements would add unneeded complexity to your code and obfuscates it. So why bother?

Pharap said:

I can't disagree with the object argument though, using tables as objects is awkward. Though it would probably make more sense if there was a decent explanation out there (that lua index that the wiki points to seems to be written to make things sound more complicated than simplifying it so people understand.) As for the local thing, that's common place in most languages. VB and C# have private, and C++ has it's equivalent. In fact most languages have more than just global and local, they have stuff like friend, protected, protected friend, public, private. The syntax changes but the concept remains. VB isn't irrelevant, it is actually used in the industry believe it or not. People hate on it because it's quite simplified and has pretty much no gaming applications, but it does have a lot of other uses like SQL compatibility and Database management (what it's generally designed for). I know that some banks use it to handle their customer databases, so it's far from irrelevant. As for which language to choose, it all depends on what you want to achieve.
Well, the other languages I know (C and Python) encapsulate variables very good from each other on different scopes and that's something I cannot reproduce in Lua even with the local statement.
As for VB, that does not seem to be something which cannot be accomplished in other languages (Python's sqlite module is quite nice as far as I can tell, have I mentioned that I'm a bit of a fan boy? ;P), but then again as don't know much about VB I don't want to judge that.



#26920 [CC1.5]ComputerCraft Emulator V0.57 (February 19th)

Posted by Ponder on 17 August 2012 - 03:45 PM in APIs and Utilities

Ah, unrelated, were can one get the source?



#26758 What is you programing / Technical experience ?

Posted by Ponder on 16 August 2012 - 10:12 PM in General

View PostPharap, on 16 August 2012 - 09:15 PM, said:

View PostPonder, on 16 August 2012 - 02:56 PM, said:

I started off with Python around nine months ago, toyed a little bit with C and a micro controller couple months later. And when I discovered this mod, well, I had to start with Lua. But I actually don't like Lua that much, rather the opposite, but it's just awesome to do this kind of stuff inside Minecraft with CC, but as a question, why do you like Lua the way you do?

I don't get why you like python and not lua.
They aren't all that different from what I can see.
Python has a few built in functions lua doesn't, but you can simply program those functions into an API for you to use.

Actually the Python standard lib is a little bit more than "a few builtins". :roll:

What annoys me most about Lua are tables. I mean, usually languages have different, encapsulated container types, but Lua puts a lot of stuff into tables which are lists, tuples, dicts/hash tables and classes in Python. That makes Lua tables broad and ambiguous, imo. e.g. I find the following outright confusing on first look:
foo = "bar"
t = {foo = foo}   -- first thought here is, "wait, I am assigning the value of foo to the value of foo?", where you actually assign the value of foo the the string "foo", ambiguous
t.foo == t ['foo'] -- same thing, if you are coming from Python this is something completely different, but Lua treats them the same.

Also Python has real objects as in "classes" not as in "you can hack classes from that one general purpose container".
Lastly, I don't ever want to miss the way Python handles exceptions. try-except-statements are pretty damn useful and elegant. Also it throws exceptions if a value is not referenced before, unlike Lua, checking for nil values is just not funny anymore, declaring any variable as local, because that's what you usually use them for, is neither.

View PostPharap, on 16 August 2012 - 09:15 PM, said:

View Postcraniumkid22, on 16 August 2012 - 03:03 PM, said:

I like lua, only because I haven't had anything to compare it to. I might go into some other sort of coding. Anytone got suggestions as to which one I would try next as a beginner? Some tools to help learn would be nice too, like an emulator.

You mean an IDE, not an emulator.
I recommend C# if you are confident or VB if you are less confident.
Don't jump straight to C++ though, it's not really a beginner's language and it's likely to frustrate you easily.
If you go for VB or C#, you can download visual studio free from microsoft

Actually, I'd suggest not getting an IDE as a beginner. Just a plain text editor with syntax highlighting will do. Helps you to get the code hammered into your brain and let's you focus on the important things.
I started with Gedit and am currently using vim.
I don't know about the languages, too. I got to admit that I haven't tried either, but VB just seems irrelevant and what you here from C++ on the web it's just overly complicated without actual gain. I'd rather suggest to start off with one of the bigger scripting languages like Python, Ruby or Perl and then move onto plain C.



#26737 [question] Am I right in thinking...

Posted by Ponder on 16 August 2012 - 09:13 PM in Ask a Pro

You can change the path, from which the API draws its information apparently via help.setPath (<path>). No Idea how those files have look like, though.



#26639 Extracting data between tags from a string - Help!

Posted by Ponder on 16 August 2012 - 03:23 PM in Ask a Pro

To extract text from tags one can do something like this:
tag = "<title>foobar</title>" -- your incoming document
pattern = "<title>(.*)</title>" -- a regular expression, it is a pattern, which matches string which fulfill this pattern
str = string.match (tag, pattern) -- str now holds "foobar"

As you can see tag and pattern are similar to one another, and the bit which is different "(.*)" actually only says match any character (.) unlimited times (*) and return them (the parenthesis).
If you want learn about it more, read this.



#26638 What is you programing / Technical experience ?

Posted by Ponder on 16 August 2012 - 03:16 PM in General

Well, I can only recommend Python. It has a huge standard library, which makes it easy for beginners to write code which gets something done. Just import a module which does all the hard work for you, which you haven't learned about yet.
Bonus for beginners, the internet is literally loaded with tutorials about it.



#26634 What is you programing / Technical experience ?

Posted by Ponder on 16 August 2012 - 02:56 PM in General

I started off with Python around nine months ago, toyed a little bit with C and a micro controller couple months later. And when I discovered this mod, well, I had to start with Lua. But I actually don't like Lua that much, rather the opposite, but it's just awesome to do this kind of stuff inside Minecraft with CC, but as a question, why do you like Lua the way you do?



#26415 How do I add a small chance of something happening?

Posted by Ponder on 15 August 2012 - 10:38 PM in Ask a Pro

You should really go with D3matt's suggestion, it's much cleaner and avoids redundancy, which is what you want as a programer.



#25814 Lua turtle help

Posted by Ponder on 13 August 2012 - 08:57 PM in Ask a Pro

Function are the only reasonable solution. Actually I don't know a reason why would not want to use them.



#25813 [CC1.5]ComputerCraft Emulator V0.57 (February 19th)

Posted by Ponder on 13 August 2012 - 08:52 PM in APIs and Utilities

Looks pretty nice, keep up the good work, mate.



#25767 Transferring variables through scripts?

Posted by Ponder on 13 August 2012 - 06:28 PM in Ask a Pro

@craniumkid
It's even easier if you use the textutils API, it has a function serialize, which turns tables into strings and an unserialize function which turns strings into tables (if they are syntactically correct, of course).

@titantyler
You open files with "io.open (<file_name>, <mode>)", where <file_name> is the path to the file you want to open and <mode> is either "w" if you want to have write access to file or "r" if read access is sufficient for your application (if you just want to read something from a file, you really should not open it in write mode, so you don't accidentally mess something up).

As an example, I use the following API to load / write data from my programs to disk:
Spoiler

EDIT: Damn, too late.



#25567 Loading Bar

Posted by Ponder on 12 August 2012 - 11:14 PM in Ask a Pro

Have a look at the Term Api. Especially the getCursorPos and setCursorPos methods together with string indexing (which is a little bit awkward in Lua) you can do something like this:

local DELAY = 0.1
local LOADING_BAR = "<=======================>"
local LOADING_TEXT = "Processing"
local LOAD = {
	LOADING_BAR,
	LOADING_TEXT,
	LOADING_BAR,
}

function writePos (char, x, y)
-- moves the cursor to the given position and writes the character $char
  term.setCursorPos (x, y)
  term.write (char)
end

function multiSlowPrint (string_table, delay)
-- string_table holds the strings which shall be printed slow across several lines, each string representing one line; delay is the time to wait between each step of the function

  local start_x, start_y = term.getCursorPos ()
  local size_x, size_y  = term.getSize ()			

  local longest_x = 0  -- we need this function to know when we have reached the end of the given strings
  for i = 1, #string_table do
	local len = #string_table [i]
	if len > longest_x then
	  longest_x = len
	end
  end

  for x = 0, size_x - 1 do
	if x >= longest_x then
	  term.setCursosPos (0, start_y + #string_table + 1)
	  break   -- if we have reached the rightmost position of our given string we want to abort the function
	end
	for y = 0, #string_table - 1 do
  
	local char = string_table [y + 1]:sub (x + 1, x +1)  -- you can read about string indexing in Lua here http://lua-users.org/wiki/StringIndexing
	if char nil == then
	  char = " "
	end

	writePos (char, x, y)

   end
  sleep (delay)
  end
end

multiSlowPrint (LOAD, DELAY)

That should be it, it's not perfect, but it should give you the idea how to do it. If you got questions just ask.



#24730 I need help with the fs API

Posted by Ponder on 09 August 2012 - 01:01 PM in Ask a Pro

Also if a function returns data you need in multiple programs, make an API out of it.


Quote

So put local in front of every variable???

Yeah, Lua is not really funny when it comes to this, guess why I cannot motivate myself to start a bigger project in CC.



#24609 I need help with the fs API

Posted by Ponder on 08 August 2012 - 10:32 PM in Ask a Pro

View Postcraniumkid22, on 07 August 2012 - 05:35 PM, said:

Ok, so since I use that same function for other parts of the code, it would probably be easier to declare a new variable like this:
cool = colors.test(rs.getBundledOutput("back"), colors.blue)
rc = colors.test(rs.getBundledOutput("back"), colors.red)
Right? And then I can pretty much do the same for everything else?
I would just call back to that variable like this:
function saveState()
local save = fs.open("status","w")
  save.writeLine("..rc..")
  save.writeLine("..cool..")
  save.close()
end
If so, then the only thing I think I might have messed up on, is the concatenation. (the two periods(..), for the newbies reading)

Actually, I'd rather avoid that, since you already have a function to access that information, so it would be redundant to have the exact same code again. You should rather generalize your functions so that they just return the string and instead of simply calling them do this:
print (coolstat ())
This way you can use same function multiple times in your program and avoid writing the same code over and over. This is what function are about, encapsulate and generalize your code to increase its re-usability and save you time.

Quote

edit: I have amended my code so it does what I think it should:
function saveState()
local save = fs.open("status","w")
  save.writeLine(username)
  save.writeLine(adminname)
  save.writeLine(userpass)
  save.writeLine(adminpass)
  save.writeLine(reactor)
  save.writeLine(coolant)
  save.writeLine(macerator)
  save.writeLine(furnace)
  save.writeLine(compressor)
  save.writeLine(extractor)
  save.writeLine(energystorage)
  save.writeLine(lights)
  save.close()
end
function loadState()
local load = fs.open("status","r")
  username = load.readLine()
  adminname = load.readLine()
  userpass = load.readLine()
  adminpass = load.readLine()
  reactor = load.readLine()
  coolant = load.readLine()
  macerator = load.readLine()
  furnace = load.readLine()
  compressor = load.readLine()
  extractor = load.readLine()
  energystorage = load.readLine()
  lights = load.readLine()
  load.close()
end
I think this is what I need it to do, but let me know. Hopefully this writes the state of each color, and then loads the state of each line written.
Take a piece of chalk, go to the next chalkboard and write a couple of times: "Global variables are bad."
Especially in ComputerCraft, since all the code on a computer is executed by the same Lua interpreter. That means by declaring a global variable you create a variable that is accessible from any other program on that computer. You don't really want that and it creates a lot of problems with debugging, imagine that one program sets a variable and another program you run afterwards uses a variable of the same name. Suddenly, the second program runs just not as it should and it will take a lot to just come up with the idea, that there might be a different programs which disturbs yours. Same goes for globals in the same program, somewhere some function is just not doing what it should because some other function messed with a global in a way it shouldn't. It's just a pain in the ass, to debug that.
If you got a lot of variables to return, just stuff them in a table and return that table instead.



#24338 I need help with the fs API

Posted by Ponder on 07 August 2012 - 05:22 PM in Ask a Pro

Two problem, first your code in saveState does not actually calls your two other functions. "..coolstat().." is just that, a string with "coolstat()" written in the middle. To actually call them and put periods around their output you need something like:
save.writeLine (".." .. coolstat () .. "..")
Second, your two functions don't return anything. write () is what it says on the tin, it writes its argument to the terminal. You don't want that, you want the function to return a string, so that saveState can write those strings to your save file. Therefor, your code should more look like:
function coolstat()
if (colors.test(rs.getBundledOutput("back"), colors.blue)) == true then
   return " Off"
elseif (colors.test(rs.getBundledOutput("back"), colors.blue)) == false then
   return " On"
else
   return " Unknown"
end
end



#23680 [Question] How can I count rednet responses

Posted by Ponder on 05 August 2012 - 12:26 PM in Ask a Pro

Yeah, the problem is, that they all get to the first call of waiting, but at that point no turtle has ever send a "done" message and even if they would have missed it anyway since the didn't listen up. You should probably make a function which constantly checks for incoming messages and run it in the background with the parallel API.

   while turtle.detect() do
	    turtle.dig()
   end
   while turtle.detectUp() do
	    turtle.digUp()
   end
   while turtle.detectDown() do
	    turtle.digDown()
   end
I don't know why you are using while here, the turtle can only detect and mine blocks directly near itself, so dig () would be called only once anyway. So I'd either put it in if clauses or just call them.
if turtle.detect () then
  turtle.dig ()
end
if turtle.detectUp () then
  turtle.digUp ()
end
if turtle.detectDown () then
  turtle.digDown ()
end

-- or simply
turtle.dig ()
turtle.digUp ()
turtle.digDown ()

Also, are you missing an "end" somewhere or is the indention just unfortunate?

Why exactly is my code not working? Have you defined a function check_message like it says in the comment? Otherwise it is almost like your code, so that's the only thing I can think of which could go wrong.



#23675 [question] Searching through a file to find and change on line

Posted by Ponder on 05 August 2012 - 12:15 PM in Ask a Pro

There are already function to do that in the Lua String API. They use Regular Expression, it is a bit tricky if you are not familiar with them, but you should check this out.



#23490 [Lua] [Question] Looking for a couple pointers (I/O)

Posted by Ponder on 04 August 2012 - 01:07 PM in Ask a Pro

Well, I think the easy way would be pretty annoying, imagine you'd have to retype a message, just because you were a character over the limit. If you really want to limit what the user can type in (why, btw?) and really don't want to handle the events yourself, just cut the stuff which is over the limit off, like the Ingame Minecraft Chat does.



#23476 [Lua] [Question] Looking for a couple pointers (I/O)

Posted by Ponder on 04 August 2012 - 11:42 AM in Ask a Pro

Nah, not really. Have a look at this.



#23455 [Lua] [Question] Looking for a couple pointers (I/O)

Posted by Ponder on 04 August 2012 - 09:23 AM in Ask a Pro

@First idea: Yeah, that would be what I also would do.
@Second idea: Well, I don't think you come around writing your own read function which pulls os events directly and counts them until a certain limit is reached.