if command not working Actionscript 3 - actionscript-3

I am making a console like program where you input text, and when you press enter, that text gets turned into the variable "code" which gets read by the if/elseif command to direct it to a certain frame.
When I did this though, actionscript completely ignored the if and just executed what was inside of the if.
There are no errors, but there is a warning. This is my full code
import flash.events.KeyboardEvent;
stop();
stage.focus=textbox;
var code:String=textbox.text;
textbox.addEventListener(KeyboardEvent.KEY_DOWN,thefunction);
function thefunction(event:KeyboardEvent){
if(event.charCode == 13){
code=textbox.text;
trace(code);
page();
}
}
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
The warning is here=
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
It says: Warning: 1100: Assignment within conditional. Did you mean == instead of =?
I then tried doing what it said, and nothing happens when I type in anything and press enter (charCode 13).
I have tried doing this with textbox.textinstead of the variable code, and still nothing happens. (trace(code) works fine, so it must be something with the bottom portion, but I'm not sure)
I am new to actionscript, so I do not know how to fix this (my excuse :D). If anybody knows how, I would love to figure out how to fix it.

first of all, as a general rule, you should never use the assignment operator (single =) in an if statement, always use the equality operator (double =)
what you're saying right now is "if you assigned the value 'red' to code without errors, then..." which of course is always true
then, to debug your problem, try to use trace("'" + code + "'"); to see exactly what your textfield contains. if you're still in doubt, convert your text in character codes and print those. Why? if there's a non-printable or non-visible character in your textfield, your if statement wouldn't match (think "red " == "red" > false)
my guess is that your textfield is set to multiline, so your enter key would be added to the text and break your check. set it to single line to avoid possible problems (if you do need a multiline input field, you need a smarter way to compare text, like using regular expressions and such ...)

Related

Unusual behavior with the Text widget indexing? (Tcl/Tk)

I am trying to create bindings for the Tk Text widget to limit the User so s/he can't delete the first character in the line (the character serves as a sort of prompt like in a terminal.)
Here's how I'm almost accomplishing this:
bind .text <BackSpace> {
if{[.text index insert] == [.text index {insert linestart+1c}]} {
break;
}
}
It works in terms of not letting the user delete the first character in the line, but for whatever reason, it also stops the user from deleting the ninth character in the line as well! For example:
>hello world!
Pressing backspace now from the end of that line will delete until
hello wor
and then stop! I can press the left-arrow to move to the next character after 'r' and keep deleting, and then as it should, it doesn't delete the carrot. I see no reason why this should be happening. If someone could either point out my mistake or let me know of a better way to achieve what I'd like that would be great.
At the point where it stops, [.text index insert] gives an index of 1.10 and [.text index {insert linestart+1c}] gives an index of 1.1.
These are numerically equal, and == likes to use numeric equality if at all possible.
The fix is to use the compare method of the text widget, perhaps like this:
bind .text <BackSpace> {
if {[.text compare insert == {insert linestart+1c}]} {
break
}
}
(I think you might actually be better off doing your overall goal a different way, perhaps by setting a tag on the text you want to preserve and checking before deletion whether any of the text to be deleted has the tag. But that's a very different approach.)

Restricting input text to numbers only

Is there a way to restrict text to nubmers only in an input textfield?
I tried using:
myInputText.restrict = "0-9";
But it had no effect. Are there any other solutions?
myInputText.restrict = "0-9\\-\\^\\\\";
Try this, this should work.
[EDIT: My method described below is an alternative to .restrict, and can theoretically allow for much finer control.]
Yes, you can, quite quickly. We're going to combine a Regex and an event listener.
First off, you're going to need to set up an event listener on the text box. I'll call the input box txtInput, for the sake of conversation. This will point to a function we'll write called validate();
txtInput.addEventListener(KeyboardEvent.KEY_DOWN, validate);
Now, we need to create our function.
function validate(evt:KeyboardEvent):void
{
var currentString:String = txtInput.text; //It is usually easier to work with the textInput contents as a string.
var numbersRegex:RegExp = /^\d*$/; //A regular expression accepting zero or more numbers ONLY.
var invalidRegex:RegExp = /\D+/; //A regular expression accepting one or more NON-numbers.
if(numbersRegex.test(currentString) == false) //Run the test. If it returns false...
{
currentString = currentString.replace(invalidRegex, ""); //Removes all non-numbers.
}
//Else, we do nothing.
txtInput.text = currentString; //Put the updated string back into the input box.
}
(Granted, that code is untested, but it should more or less work.)
The logic going on here: The user enters a character into the box. The event listener fires as soon as the key is pressed. If the string isn't 100% numbers, then the string is searched for all non-number characters, and those characters are removed.
EDIT AS REQUESTED: Also, make sure you don't have conflicting instance names. If you have two input boxes with the same name, Flash may be looking at the wrong one.
txtInput.text = "Sample text." should throw a compiler error if there's a duplicate, or in the worst case, show you which input box you ARE affecting.

Why doesn't the cursor stay at the same place?

I have a very strange problem which I can't resolve after trying the whole morning.
This is my function and mapping:
nnoremap ,zz :call SwapAW("2-2","5")<CR>
nnoremap ,zc :call SwapAW("2-2","5")<CR>
function! SwapAW(keyw,number)
let li = line('.')
let co = col('.')
exe "call cursor(li,co)"
let linew= line('.')
let conew= col('.')
echo linew conew
endfunction
,zc --> moves the cursor to the right
,zz --> the cursor stays where it is
I changed everything but can't find out why the cursor doesn't stay where it is in both cases.
I changed p.e. the mapping, from ,zc to ,zd and ,zz to ,zw (tried others as well) and changed the leaderkey from , to \, and tried to swap both mapping lines.
Nothing changes.
What's happening?
What did I wrong?
Thanks in advance.
You have a trailing <Space> character in your ,zc mapping (after the <CR>). That moves the cursor after the function invocation.
With mappings, one must be careful with hidden characters. Therefore, it's advisable (and sometimes, e.g. at the beginning of a mapping, necessary) to literally write the special form <Space> when you actually need to include one.
My ShowTrailingWhitespace plugin will highlight those trailing spaces and tabs, as many code guidelines frown on them. The plugin page also contains links to alternatives.

Sublime Text 2, faster alternative to find and replace regex?

$_POST['daily_limit'];
$whatever = $_POST['smoke'];
$_POST['soup'] + $_POST['cake'];
to
$this->input->post('daily_limit');
$whatever = $this->input->post('smoke');
$this->input->post('soup') + $this->input->post('cake');
In this example, is there any faster way to switch from $_POST[] to $this->input->post() without writing up a regular expression find and replace? I don't care if it takes multiple steps. Writing the regex for this (find: \$_POST\[(.*?)\] replace: \$this->input->post\($1\)) takes longer than changing them all manually (maybe I'm just not good at regex). Any ideas?
I'm making a brash assumption here, that you have only one variable within each pair of brackets and that the variables only contain alphanumeric characters. ['soup'+'bacon'] will break this trick, as will ['soup-with-bacon'].
With your cursor, highlight an instance of $_POST[ - nothing else.
Hit Alt+F3 if you're on Windows/Linux (Cmd+ShiftG in Mac?)
Try to scroll through and see if everything that's selected is everything you want to replace.
Type $this->input->post( - nothing else.
Press → to move all cursors to the right of the first quote.
Press Ctrl+→ (this is the only remotely wtfh4xxy part of the process, and only if you're not used to navigating by word with the cursor) to navigate over the variable.
Press → twice to move all cursors to the right of the next quote.
Replace the ]with a ).
#nnnn I did a variation of your version to remove the wtfh4xxy part.
select:$_POST
altf3
type: $this->input->post(
ctrlshiftm
ctrlx
ctrlshiftm
ctrlv
type: )
Sublime text ftw!

Deleting entire function definition in Vim

I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.
For example, if I have a function like this:
void helloworlds( int num )
{
int n;
for ( n = 0; n < num; ++n ) {
printf( "Hello World!\n" );
}
}
How would I be able to delete the whole definition including the function name?
As is common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines.
If your cursor is on the line with the function name, try d}. It will delete everything to the next block (i.e. your function body).
Within the function body itself, dap will delete the 'paragraph'.
You can delete a curly brace block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using / and ? with that regex I mentioned above. Combine with the d motion, and you acheive the same effect. In addons like Python-mode, these operators are redefined to mean exactly what you're looking for: move from function to function.
How to delete the whole block, header included
If you're on the header/name, or the line before the block, da} should do the trick.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader> shortcut out of it.
Plugins
I don't do much C programming in Vim, but there are surely plugins to help with such a thing. Try Vim Scripts or their mirror at GitHub.
To delete an entire function, including its definition, such as:
function tick() {
// ...
}
Move to the line with the function name.
Move the cursor to the opening brace, f{ should do it, or simply $.
Press V%d (Visual line, move to matching pair, delete)
If your functions look like this:
function tick()
{
// ...
}
Move to the line with the function name.
Press J (join the current line with line bellow. This also puts your cursor at the last character on the resulting line, {, just the one we need for the next command.)
Press V%d (Visual line, move to matching pair, delete.)
or
Move to the line with the function name.
Press V[Down]%d (Visual line, move one line down, move to matching pair, delete.)
If you are willing to install plugins vim-textobj-function will give you vif for Visual select Inside Function and vaf for Visual select A Function.
daf will delete the function, both the line with the signature and the function body ({})
The text object defined by this plugin are more specific and they don't rely on the function body being a contiguous block of text or { being placed at the first character on the line.
The drawback is that you depend on an external plugin.
You can use this shortcut to delete not only the function, also the lines between curly braces, i.e the code between if-else statements,while,for loops ,etc.
Press Shitf + v [Will get you in visual Mode] at the curly brace start/end.
Then Press ] + } i.e ] + Shitf ] - If you are in start brace.
Then Press [ + { i.e [ + Shitf [ - If you are in end brace.
Then DEL to delete the lines selected.
The simplest and most direct way way is as follows (works anywhere inside function):
v enter visual mode
{ move to first brace in function (may have to press more than once)
o exchange cursor from top to bottom of selection
} extend selection to bottom of function
d delete selected text
The complete command sequence would be v{o}d. Note that you can do other operations besides delete the same way. For example, to copy the function, use y (yank) instead of d.
Use this simple way
1.Go to the function definition
2.dd - delete function definition
3.d -start delete operation
4.shift+5(%) - delete the lines between { to }
If your function were separated by the blank lines, just type:
dip
which means "delete inner paragraph".
Another way is to go to the line of the start of your function and hit: Vj% (or V%% if your style puts the opening brace on the same line). This puts you into Visual-Line mode and the percent takes you to the matching closing brace. In the second style, the first % takes you to the opening brace on the line that you selected and the second to its matching closing brace.
Also works for parentheses, brackets, C-style multi-line comments and preprocessor directives.
See the manual for more info.
Pre-condition: be somewhere inside the function.
Go to the previous closing curly bracket on the first line using
[]
Then delete down to the next closing curly bracket on the first line using
d][
Most posted methods have a downside or two. Usually, when working withing a class definition of some object oriented language, you might not have an empty line after the function body, because many code formatters put the closing braces of last method and class on consecutive lines. Also, you might have annotations on top of the function. To make matters worse, there might be empty lines within your function body. Additionally you'd prefer a method that works with the cursor anywhere within the function, because having to move it to a specific line or worse, character, takes valuable time. Imagine something like
public class Test {
/* ... */
#Test
public void testStuff() {
// given
doSetup();
// when
doSomething();
// then
assertSomething();
}
}
In this scenario, vap won't do you any good, since it stops at the first empty line within your function. v{o} is out for the same reason. va{V is better but doesn't catch the annotation on top of the method. So what I would do in the most general case is va{o{. va{ selects the whole function body (caveat: if your cursor is within a nested block, for instance an inner if statement, then you'll only get that block), o puts the cursor to the beginning of the selection and { selects the whole paragraph prepending your selection. This means you'll get the function definition, all annotations and doc comments.
the most easy way I found is:
Get to the line where the function starts and do this: ^^vf{% to mark the entire function and then whatever you like.
^^ - start of the line
v - start visual mode
f - jump to the next search character
{ - this is the search character
% - jump to the closing brackets
This is also very logical after you have used it a few times.
non-visual way:
d/^}/e
... delete by searching for } at line beining, including it for deletion.
without /e (not mentioned in above answers), solution is incomplete.
with /e - searching goes to end of match, so closing bracket is included, and command is well for yanking too:
y/^}/e
if you use neovim version :>0.5
the modern way is to use treesitter and build your model, then you can be selected or yanked or deleted...
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited
I suggested this video on youtube to learn how to use treesitter to build your model : Let's create a Neovim plugin using Treesitter and Lua
I tried all the top answers here, but none of them works except the one by Nick which suggests to press f{ to get to the opening curly brace. Then V%d to delete the whole function.
Note that, the whole function gets yanked, so you can paste it elsewhere. I come across this use-case frequently, especially when moving if blocks inside another.
I use this map. It work for me
"delete function definition
"only support function body surround by {}
nnoremap <LEADER>df {v/{<cr>%d