Alternatives of goto and jump commands - language-agnostic

I am working on a language where there is not any goto,jump function. For example, Matlab.
Can you please help me on how to avoid using it? Is there any simple trick solving my problem?

You should consider using break and continue
Instead of:
for ...
...
if ...
goto nextstuff:
end
end
nextstuff:
You can do:
for ...
...
if ...
break
end
end
And as #andrey said, you can often replace goto by if-else
Instead of doing:
if cond
goto label
end
...
foobar()
...
label:
foobar2()
you can do:
if ~cond
...
foobar()
...
end
foobar2()
When you use a goto to go back, you can replace it by a while:
Instead of doing:
redothat:
foobar()
...
if cond
goto redothat;
end
you can do:
while cond
foobar()
...
end

Well, first of all you might as well ask it without the matlab tag, you might get better answers. That is because this kind of question is common to almost all of the modern languages.
Instead of goto and jump you should use either conditionals like if,if-else or loops like while,for, depending on what you want to achieve.
Check out GOTO still considered harmful?, Why is goto poor practise?.

As #Andrey mention you can use if or if-else statement. In many cases loops like while, for is one-to-one replacements to the if-else and goto.
You should also consider to use break and continue statement as #Oli said above.
In some rare cases you can use exception (I don't know whether the Matlab supports it) in order to "go back". This is somewhat controversial, but maybe in your case it will fit.
redothat:
foobar()
...
And inside foobar() in some place you have
if cond
goto redothat;
end
you can do:
while(true){
try {
foobar();
...
break;
}
catch(YourApplicationException e){
//do nothing, continiue looping
}
}
And inside foobar() in some place you have
if cond
throw YourApplicationException();
end
Or you can do something like this:
you can do:
boolean isOk = false;
while(! isOk){
try {
foobar();
...
isOk=true;
}
catch(YourApplicationException e){
//do nothing, continiue looping
}
}

Related

Mysterious stackoverflow in function call?

I'm creating a Lua program and I tried to use something like inheritance, but I got a stack overflow when I called the super of the function.
function Parent()
local self = {}
self.println = function(text) print(text) end
return self
end
function Child()
local super = Parent()
local this = {}
this.println = function(text)
super.println(text) -- According to the debugger, here is the problem.
print("Child")
end
for k, v in pairs(this) do
super[k] = v
end
return this
end
local a = Child()
a.println("Hello!")
I know there are other ways to do this, but I must use this kind of "OOP". Can anyone recommend me anything?
Your problem is with the loop that makes all println functions be the same println function that redirects the call to another printnl function, which is actually the same print function, creating a loop.
for k, v in pairs(this) do
super[k] = v
end
Removing that loop will make the code work, but I am not sure if this makes it behave as you wanted.
Maybe you should take a look at lua metatables if you want to inherit methods.
That for k, v in pairs(this) do loop seems backwards to me.
You are pushing the this copies of the functions into the super table (overwriting the ones that are already there).
So you push this.println into super and then call super.println inside it and you end up calling yourself repeatedly.
Did you mean to do that the other way around? Copy the super functions into this? Or what was the point with that loop in the first place?

Opposite of 'else' during a switch or conditional

I'm wondering if any programming language has an operator like so (ALWAYS is a placeholder--I'm asking what language has something like ALWAYS)
if a
doAStuff()
else if b
doBStuff()
ALWAYS
//runs if a or b is true
win()
else
doElse()
Basically, the opposite of else. It runs if something else in the statement ran.
logically, it would be like this
always = true
if a
doA()
else if b
doB()
else
always = false
doElse()
if always
win()
Does any language have that logic built into a keyword, such as ALWAYS from the first example?
Not really 'language-agnostic'. More like 'find-my-language'. With Forth and Lisp you can add such a construct naturally to the language, and it will work just like existing constructs. I'm not aware of any language that has it by default. If you have a less extensible language than Forth or Lisp, then the natural ways to do this are to use a local function (if you have first-class functions) or to set a flag as you show, or else to factor the code such that both conditions can be treated as pairs without a lot of repetition.
So, in JavaScript:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) { doB(); if (a) both() }
else neither()
})()
At upon reading that, it should be clear that the 'both' case is never going to happen in that second block. So this simplifies to:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) doB()
else neither()
})()
Which doesn't seem worth the effort. So it seems even less worth a language feature. Why not go further and write this?
if (a) { doA(); if (b) { win(); more stuff, potentially } }
else if (b) doB()
else neither()
If b is an expensive test, just save the result of it. If b must not be tested before a, save both results. Obviously, both tests must always be run anyway.
;(function() {
var a = testA(),
b = testB()
... as above ...
})()
As for the last option, "factor the code such that both conditions can be treated as pairs", what you're looking for is:
if (a && !b) doA()
if (!a && b) doB()
if (a && b) { doA(); doB(); win() } // or no doB() if you really want that
if (!a && !b) neither()
With else if if you like. I'd prefer this option actually in a pattern-matching language. Mercury will even throw an compile-time error if you forget one of the four possible outcomes.
Not sure if this is what you're looking for, but a simple do-while loop will ALWAYS run at least once in Java.

How to return to base function/script

Does anyone know how to return to a base function/script (f/s) when inside a f/s that's called by a f/s that was called by the base f/s? Confusing I know...
base f/s - f/s - f/s --> return from here to base f/s
The regular return call will only get me to the f/s one level above.
I'm currently using a try-catch construct in the base f/s to find when the program errors out, but I feel like this is a less than ideal way of doing this.
Thanks, and if I can clarify any other way please let me know.
I advise against using a try catch block to achieve this behavior, unless an actual error or exception has occurred. Going this route will result in code that isn't clear.
Instead, have the inner function return a value indicating some status. Then evaluate that status in the middle function to determine if the middle function should return as well.
Here is a simple example
function outer()
middle();
end
function middle()
innerResult = inner()
switch innerResult
case 1:
disp('Executing the guts of middle()');
case -1:
return;
end
end
function retVal = inner()
if returnToOuter
return -1;
else
return 1;
end
end

How to use goto label in MySQL stored function

I would like to use goto in MySQL stored function.
How can I use?
Sample code is:
if (action = 'D') then
if (rowcount > 0) then
DELETE FROM datatable WHERE id = 2;
else
SET p=CONCAT('Can not delete',#b);
goto ret_label;
end if;
end if;
Label: ret_label;
return 0;
There are GOTO cases which can't be implemented in MySQL, like jumping backwards in code (and a good thing, too).
But for something like your example where you want to jump out of everything to a final series of statements, you can create a BEGIN / END block surrounding the code to jump out of:
aBlock:BEGIN
if (action = 'D') then
if (rowcount > 0) then
DELETE FROM datatable WHERE id = 2;
else
SET p=CONCAT('Can not delete',#b);
LEAVE aBlock;
end if;
end if;
END aBlock;
return 0;
Since your code is just some nested IFs, the construct is unnecessary in the given code. But it makes more sense for LOOP/WHILE/REPEAT to avoid multiple RETURN statements from inside a loop and to consolidate final processing (a little like TRY / FINALLY).
There is no GOTO in MySQL Stored Procs. You can refer to this post:
MySQL :: Re: Goto Statement

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.