<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SlashCode &#187; C/C++</title>
	<atom:link href="http://davideaversa.it/slashcode/category/guide/cc/feed/" rel="self" type="application/rss+xml" />
	<link>http://davideaversa.it/slashcode</link>
	<description></description>
	<lastBuildDate>Thu, 03 May 2012 14:28:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Quick Fix: error while loading shared libraries</title>
		<link>http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/</link>
		<comments>http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 17:46:17 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Generale]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[librerie]]></category>
		<category><![CDATA[sistema operativo]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=790</guid>
		<description><![CDATA[Salve a tutti e ben tornati dalle vacanze!Per riprendere un po&#8217; il ritmo con il blog vi propongo dei mini-post che rispondono velocemente ai più comuni problemi di compilazione ed esecuzione di programmi. Il primo problema che risolveremo è il seguente error while loading shared libraries: libXXX.so: cannot open shared object file: No such file <a href='http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F09%2Fquick-fix-error-while-loading-shared-libraries%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Quick Fix: error while loading shared libraries" data-url="http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p>Salve a tutti e ben tornati dalle vacanze!Per riprendere un po&#8217; il ritmo con il blog vi propongo dei mini-post che rispondono velocemente ai più comuni problemi di compilazione ed esecuzione di programmi.</p>
<p>Il primo problema che risolveremo è il seguente</p>
<div class="codecolorer-container bash dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">error <span style="color: #000000; font-weight: bold;">while</span> loading shared libraries: libXXX.so: cannot open shared object file: No such <span style="color: #c20cb9; font-weight: bold;">file</span> or directory</div></div>
<p>A chi non è capitato almeno una volta nella vita?</p>
<p><span id="more-790"></span></p>
<p><strong>PREMESSA:</strong></p>
<p>Ogni applicazione sul vostro sistema usa delle <strong>librerie</strong>. Una libreria non è altro che un insieme di codice già pronto e compilato che esegue delle funzioni specifiche. Questo permette ad ogni sviluppatore di <em>non reinventare la ruota ogni volta</em> ma di utilizzare il codice già scritto da altri.</p>
<p>Una libreria può essere <strong>statica</strong> (.a) o <strong>dinamica</strong> (.so o .dll su Windows). Nel primo caso la libreria viene inglobata nell&#8217;eseguibile in fase di compilazione, nel secondo invece la libreria è un file separato che viene agganciato all&#8217;eseguibile durante il caricamento del programma da un componente del sistema operativo chiamato <strong>linker dinamico</strong>.</p>
<p>Ovviamente le librerie dinamiche ottimizzano meglio le risorse evitando che del codice uguale venga replicato inutilmente in ogni eseguibile.</p>
<p><strong>CAUSA:</strong></p>
<p>Il messaggio di errore non lascia alcun dubbio: la libreria dinamica non è presente nel sistema o il linker dinamico non riesce a trovarla.</p>
<p><strong>SOLUZIONE:</strong></p>
<p>Se la causa è semplice la soluzione è altrettanto semplice.</p>
<p>Per prima cosa accertiamoci che la libreria sia installata e presente nel nostro sistema. Possiamo verificarlo agilmente con</p>
<p><code class="codecolorer text dawn"><span class="text">locate libXXX.so</span></code></p>
<p>Che restituirà il percorso della libreria.</p>
<p>Se la libreria è stata installata durante la sessione corrente allora dobbiamo forzare l&#8217;aggiornamento del database con</p>
<p><code class="codecolorer text dawn"><span class="text">sudo updatedb</span></code></p>
<p>A questo punto probabilmente la libreria si troverà in un percorso non standard. Non ci resta che aggiungere questo percorso nella lista dei percorsi scandagliati dal linker.</p>
<p>Per fare questo apriamo il file <code class="codecolorer text dawn"><span class="text">/etc/ld.so.conf</span></code> (o creiamo un file nella cartella <code class="codecolorer text dawn"><span class="text">/etc/ld.so.conf.d/</span></code>) e inseriamoci dentro il percorso della libreria, ad esempio:</p>
<p><code class="codecolorer text dawn"><span class="text">/usr/local/lib</span></code>.</p>
<p>A questo punto chiamiamo</p>
<p><code class="codecolorer text dawn"><span class="text">sudo ldconfig</span></code></p>
<p>per aggiornare la cache del linker. </p>
<p>E il gioco è fatto.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=790&amp;md5=73d45dff39a2dba303463570623e8199" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/09/quick-fix-error-while-loading-shared-libraries/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F09%2Fquick-fix-error-while-loading-shared-libraries%2F&amp;language=it_IT&amp;category=text&amp;title=Quick+Fix%3A+error+while+loading+shared+libraries&amp;description=Salve+a+tutti+e+ben+tornati+dalle+vacanze%21Per+riprendere+un+po%26%238217%3B+il+ritmo+con+il+blog+vi+propongo+dei+mini-post+che+rispondono+velocemente+ai+pi%C3%B9+comuni+problemi+di+compilazione+ed...&amp;tags=librerie%2Csistema+operativo%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Un cocktail a base di Fortran, C++ e Lua</title>
		<link>http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 17:49:06 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[fortran]]></category>
		<category><![CDATA[lua]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=744</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/"><img title="Un cocktail a base di Fortran, C++ e Lua" src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/threeway-150x150.jpg" alt="Un cocktail a base di Fortran, C++ e Lua"  width="200" height="200" /></a></div><br/>Mi hanno fatto una domanda nei commenti molto interessante: come posso sfruttare Lua con del codice Fortran? Bene, ho trovato una soluzione piuttosto semplice ed interessante per cui ho deciso di scriverci sopra un bel post. Per prima cosa sappiate che non c&#8217;è un vero modo per collegare Lua a Fortran direttamente. Lua ha la <a href='http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fun-cocktail-a-base-di-fortran-c-e-lua%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Un cocktail a base di Fortran, C++ e Lua" data-url="http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><a href="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/threeway.jpg"><img src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/threeway-150x150.jpg" alt="" title="Bivio" width="150" height="150" class="alignleft size-thumbnail wp-image-745" /></a></p>
<p>Mi hanno fatto una domanda nei commenti molto interessante: come posso sfruttare Lua con del codice Fortran? Bene, ho trovato una soluzione piuttosto semplice ed interessante per cui ho deciso di scriverci sopra un bel post.</p>
<p>Per prima cosa sappiate che non c&#8217;è un vero modo per collegare Lua a Fortran direttamente. Lua ha la sua libreria in C, pensata per il C e funziona per il C. Anche cercando in giro non ho trovato nulla che permetta il collegamento diretto. Tuttavia il Fortran e il C/C++ sono collegabili nativamente! Per questo motivo il procedimento si sintetizza in due punti</p>
<ul>
<li>Collegare le funzioni Fortran alle funzioni C++</li>
<li>Collegare Lua alle funzioni C++</li>
</ul>
<p>In questo modo il C++ assume il ruolo di collante fra Fortran e Lua e tutto funziona a meraviglia ma non solo: nonostante l&#8217;approccio a tre vie l&#8217;implementazione è formidabilmente trasparente e intuitiva!</p>
<p>Poiché sappiamo già come collegare Lua al C++ comincerò a far vedere come collegare Fortran a C++. Cominciamo con il codice C++ di esempio.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &lt;iostream&gt;</span><br />
<br />
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; <span style="color: #0000ff;">void</span> ffunction_<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">float</span> <span style="color: #000040;">*</span>a, <span style="color: #0000ff;">float</span> <span style="color: #000040;">*</span>b<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">float</span> a <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">float</span> b <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; ffunction_<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>a,<span style="color: #000040;">&amp;</span>b<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> a <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; &quot;</span> <span style="color: #000080;">&lt;&lt;</span> b <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Il programma è stupido, lo so, ma rende l&#8217;idea. In pratica lasciamo che la funzione <code class="codecolorer text dawn"><span class="text">ffunction_</span></code> vada a modificare i valori delle due variabili <code class="codecolorer text dawn"><span class="text">a</span></code> e <code class="codecolorer text dawn"><span class="text">b</span></code> e poi stampiamo i nuovi valori.</p>
<p>Ma cosa fa <code class="codecolorer text dawn"><span class="text">ffunction_</span></code>? Questa è la nostra funzione Fortran e nel codice C++ dobbiamo solo assicurarci che sia definita come <code class="codecolorer text dawn"><span class="text">extern</span></code>. Il codice di questa funzione è semplice ed è salvato nel file <code class="codecolorer text dawn"><span class="text">ffunction.f</span></code>.</p>
<div class="codecolorer-container fortran dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="fortran codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp; &nbsp; &nbsp; <span style="color: #b1b100;">subroutine</span> ffunction<span style="color: #009900;">&#40;</span>a,b<span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; a<span style="color: #339933;">=</span><span style="color: #cc66cc;">3.0</span><br />
&nbsp; &nbsp; &nbsp; b<span style="color: #339933;">=</span><span style="color: #cc66cc;">4.0</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #b1b100;">end</span></div></div>
<p>Ora come compiliamo? Semplicissimo.</p>
<ul>
<li>Prima compiliamo il codice C++ con <code class="codecolorer text dawn"><span class="text">g++ esempio.cpp -c</span></code> ottenendo il file <code class="codecolorer text dawn"><span class="text">esempio.o</span></code></li>
<li>Poi compiliamo il codice fortran con <code class="codecolorer text dawn"><span class="text">gfortran ffunction.f -c</span></code> ottenendo il file <code class="codecolorer text dawn"><span class="text">ffunction.o</span></code></li>
<li>Infine uniamo il tutto con <code class="codecolorer text dawn"><span class="text">g++ -o esempio esempio.o ffunction.o</span></code> ottenendo l&#8217;eseguibile <code class="codecolorer text dawn"><span class="text">esempio</span></code></li>
</ul>
<p>Niente di più semplice. In pratica, salvo definire le funzioni fortran come extern e l&#8217;uso di un compilatore diverso, l&#8217;integrazione fra fortran e C++ è praticamente trasparente!</p>
<p>A questo punto collegare Lua al Fortran è praticamente IDENTICO a collegare Lua al C++. Le nostre funzioni LuaGlue non faranno altro che chiamare funzioni Fortran come se stessero chiamando una funzione C++.</p>
<p>Supponiamo di voler chiamare una funzione Fortran che calcoli il fattoriale di un numero come nel caso di esempio di un articolo precedente:</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">LuaGlue _FortranFactorial<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">struct</span> lua_State <span style="color: #000040;">*</span>pLuaState<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">double</span> n<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;n <span style="color: #000080;">=</span> pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetNumberArgument<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #ff0000; font-style: italic;">/* Calcoliamo il fattoriale */</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">int</span> res <span style="color: #000080;">=</span> fortran_factorial_recursive_<span style="color: #008000;">&#40;</span>n<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #ff0000; font-style: italic;">/* Restituiamo il valore di ritorno */</span><br />
&nbsp; &nbsp; &nbsp;pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>PushNumber<span style="color: #008000;">&#40;</span>res<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Il codice è identico salvo che <code class="codecolorer text dawn"><span class="text">fortran_factorial_recursive_</span></code> questa volta non è una funzione C ma una funzione Fortran definita nel modo che abbiamo visto in precedenza.</p>
<p>E se siete abilissimi programmatori Fortran ma non sapete nulla di C++? Non credo sia un grosso problema, in questo approccio tutta la programmazione è eseguita in Fortran e Lua. Di C++ è necessario sapere proprio le basi e l&#8217;uso di LuaGrip per agganciare le funzioni a Lua, nulla più. Una piccola scocciatura e un piccolo sforzo iniziale in più per avere un integrazione Lua/Fortran praticamente perfetta.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=744&amp;md5=14e9f60a50c90ede0722fae4e78e82f3" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/un-cocktail-a-base-di-fortran-c-e-lua/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fun-cocktail-a-base-di-fortran-c-e-lua%2F&amp;language=it_IT&amp;category=text&amp;title=Un+cocktail+a+base+di+Fortran%2C+C%2B%2B+e+Lua&amp;description=Mi+hanno+fatto+una+domanda+nei+commenti+molto+interessante%3A+come+posso+sfruttare+Lua+con+del+codice+Fortran%3F+Bene%2C+ho+trovato+una+soluzione+piuttosto+semplice+ed+interessante+per+cui+ho+deciso...&amp;tags=C%2Cfortran%2Clua%2Cblog" type="text/html" />
	</item>
		<item>
		<title>LUAding and Saving</title>
		<link>http://davideaversa.it/slashcode/2011/06/luading-and-saving/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/luading-and-saving/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 19:35:44 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[lua]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=741</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2011/06/luading-and-saving/"><img title="LUAding and Saving" src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Loading-150x150.jpg" alt="LUAding and Saving"  width="200" height="200" /></a></div><br/>Qualunque programma che si rispetti, e a maggior ragione un gioco, ha necessità di salvare dati in modo tale da recuperarli negli avvii successivi. Il primo metodo che viene in mente consiste nello scrivere i dati in un file che, in fase di caricamento, verrà passato ad un parser per recuperare le informazioni. Scrivere un <a href='http://davideaversa.it/slashcode/2011/06/luading-and-saving/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluading-and-saving%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/luading-and-saving/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="LUAding and Saving" data-url="http://davideaversa.it/slashcode/2011/06/luading-and-saving/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><a href="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Loading.jpg"><img src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Loading-150x150.jpg" alt="" title="Loading" width="150" height="150" class="alignleft size-thumbnail wp-image-742" /></a></p>
<p>Qualunque programma che si rispetti, e a maggior ragione un gioco, ha necessità di salvare dati in modo tale da recuperarli negli avvii successivi. Il primo metodo che viene in mente consiste nello scrivere i dati in un file che, in fase di caricamento, verrà passato ad un parser per recuperare le informazioni.</p>
<p>Scrivere un parser però è piuttosto impegnativo e necessita di un bel po&#8217; di lavoro. Ma pensiamoci bene. Noi un parser già pronto ce l&#8217;abbiamo: LUA! Esattamente! Sfruttiamo Lua come parser per recuperare le informazioni!</p>
<div class="codecolorer-container lua dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="lua codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">-- Base Lua Script for Load/Save</span><br />
<br />
<span style="color: #808080; font-style: italic;">-- Default Value</span><br />
<br />
nome <span style="color: #66cc66;">=</span> <span style="color: #ff6666;">&quot;NONE&quot;</span><br />
visite <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">0</span><br />
<br />
<span style="color: #808080; font-style: italic;">-- Check if one file exists or not</span><br />
<span style="color: #aa9900; font-weight: bold;">function</span> file_exists<span style="color: #66cc66;">&#40;</span>name<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp;<span style="color: #aa9900; font-weight: bold;">local</span> f<span style="color: #66cc66;">=</span><span style="color: #0000aa;">io.open</span><span style="color: #66cc66;">&#40;</span>name<span style="color: #66cc66;">,</span><span style="color: #ff6666;">&quot;r&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp;<span style="color: #aa9900; font-weight: bold;">if</span> f<span style="color: #66cc66;">~=</span><span style="color: #aa9900;">nil</span> <span style="color: #aa9900; font-weight: bold;">then</span> <span style="color: #0000aa;">io.close</span><span style="color: #66cc66;">&#40;</span>f<span style="color: #66cc66;">&#41;</span> <span style="color: #aa9900; font-weight: bold;">return</span> <span style="color: #aa9900;">true</span> <span style="color: #aa9900; font-weight: bold;">else</span> <span style="color: #aa9900; font-weight: bold;">return</span> <span style="color: #aa9900;">false</span> <span style="color: #aa9900; font-weight: bold;">end</span><br />
<span style="color: #aa9900; font-weight: bold;">end</span><br />
<br />
<span style="color: #aa9900; font-weight: bold;">function</span> SaveData<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; myfile <span style="color: #66cc66;">=</span> <span style="color: #0000aa;">io.open</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;savegame.lua&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;w&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">if</span> myfile <span style="color: #66cc66;">~=</span> <span style="color: #aa9900;">nil</span> <span style="color: #aa9900; font-weight: bold;">then</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;-- Test Lua SaveGame file&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%s&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;-- File created on: &quot;</span><span style="color: #66cc66;">,</span> <span style="color: #0000aa;">os.date</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%s%s&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;nome = <span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #66cc66;">,</span>nome<span style="color: #66cc66;">,</span><span style="color: #ff6666;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%d&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;visite = &quot;</span><span style="color: #66cc66;">,</span>visite<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; myfile<span style="color: #66cc66;">:</span><span style="color: #0000aa;">write</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.char</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">io.close</span><span style="color: #66cc66;">&#40;</span>myfile<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">end</span><br />
<span style="color: #aa9900; font-weight: bold;">end</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
<span style="color: #aa9900; font-weight: bold;">function</span> LoadData<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">if</span> file_exists<span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;savegame.lua&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #aa9900; font-weight: bold;">then</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">dofile</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;savegame.lua&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">end</span><br />
<span style="color: #aa9900; font-weight: bold;">end</span><br />
<br />
<span style="color: #aa9900; font-weight: bold;">function</span> Saluti<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">if</span> visite <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">0</span> <span style="color: #aa9900; font-weight: bold;">then</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Ciao! E' la prima volta che avvii il programma!&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Dimmi il tuo nome:&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; nome <span style="color: #66cc66;">=</span> <span style="color: #0000aa;">io.stdin</span><span style="color: #66cc66;">:</span><span style="color: #0000aa;">read</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; visite <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">1</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">else</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; tmp <span style="color: #66cc66;">=</span> <span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%s%s&quot;</span><span style="color: #66cc66;">,</span><span style="color: #ff6666;">&quot;Ciao &quot;</span><span style="color: #66cc66;">,</span> nome<span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;! Sei tornato!&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span>tmp<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; tmp <span style="color: #66cc66;">=</span> <span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%d&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;Il tuo numero di visite e' &quot;</span><span style="color: #66cc66;">,</span> visite<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span>tmp<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; visite <span style="color: #66cc66;">=</span> visite <span style="color: #66cc66;">+</span> <span style="color: #cc66cc;">1</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">end</span><br />
<span style="color: #aa9900; font-weight: bold;">end</span><br />
<br />
LoadData<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
Saluti<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
SaveData<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></div></div>
<p>Diamo un occhiata al listato precedente. Cominciamo dalla funzione <code class="codecolorer text dawn"><span class="text">Saluti</span></code>. Questa funzione rappresenta ciò che fa il programma: ti saluta e ti ricorda il numero di volte che lo hai avviato. Ovviamente, se è la prima volta che il programma viene avviato vi verrà richiesto il nome.</p>
<p>Ma tutto questo non ci interessa molto. Passiamo al cuore: la funzione <code class="codecolorer text dawn"><span class="text">SaveData()</span></code>. Questa funzione è sicuramente la funzione più interessante. Come potete vedere il codice crea un file e lo riempie con del codice Lua valido che rappresenta i dati da salvare. Nel mio caso, ad esempio, il file <code class="codecolorer text dawn"><span class="text">savegame.lua</span></code> contiene</p>
<div class="codecolorer-container lua dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="lua codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">-- Test Lua SaveGame file</span><br />
<br />
<span style="color: #808080; font-style: italic;">-- File created on: Thu Jun 23 21:21:08 2011</span><br />
<br />
nome <span style="color: #66cc66;">=</span> <span style="color: #ff6666;">&quot;Davide Aversa&quot;</span><br />
visite <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">7</span></div></div>
<p>In questo semplice caso, in cui le uniche cose da salvare sono il nome e il numero di visite il file darà di sole 4 righe (commenti compresi) ma questo discorso vale anche in generale e per salvataggi di complessità arbitraria! La funzione SaveGame è solitamente lunga e complessa ma piuttosto facile da gestire anche per salvataggi complicati.</p>
<p>Il vantaggio di questa tecnica appare chiarissimo non appena leggiamo la funzione <code class="codecolorer text dawn"><span class="text">LoadData</span></code>. Due righe (in realtà basterebbe solo <code class="codecolorer text dawn"><span class="text">dofile</span></code>). Non è stupendo? Abbiamo sostituito righe e righe di parser con un solo comando sfruttando il linguaggio stesso: un chiaro esempio di meta-programmazione applicata ad un operazione fondamentale come il salvataggio e la scrittura dei file.</p>
<p>Quando Lua esegue il file savegame automaticamente ingloba tutte le funzioni contenute nel file e, inoltre, questo formato permette agli sviluppatori di agire facilmente sul salvataggio in modo tale da &#8220;creare&#8221; manualmente salvataggi di situazioni particolari a scopo di debug!</p>
<p>Questo è uno dei metodi di salvataggio dati più facile, efficiente e veloce che io conosca.</p>
<p>Potete provare il programma in questione semplicemente dando</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">lua loadsave.lua</div></div>
<p>Buon divertimento e buon salvataggio.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=741&amp;md5=c67ab8aba3711e0fa00527ea417df612" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/luading-and-saving/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluading-and-saving%2F&amp;language=it_IT&amp;category=text&amp;title=LUAding+and+Saving&amp;description=Qualunque+programma+che+si+rispetti%2C+e+a+maggior+ragione+un+gioco%2C+ha+necessit%C3%A0+di+salvare+dati+in+modo+tale+da+recuperarli+negli+avvii+successivi.+Il+primo+metodo+che+viene+in...&amp;tags=lua%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Lua&#8217;s TATP Tutorial Code</title>
		<link>http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 21:24:47 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=735</guid>
		<description><![CDATA[A parte il nome esotico, volevo presentarvi Lua&#8217;s Totally Awesome Tutorial Pack xD Un modo esagerato e divertente per dirvi che ho raccolto tutto il codice degli scorsi tutorial su Lua e C++ in un comodo file tar.gz. All&#8217;interno trovate anche l&#8217;ultimissima versione di LuaGrip. DOWNLOAD Per prima cosa dovete installare LuaGrip. Per fare questo <a href='http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluas-tatp-tutorial-code%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Lua&#8217;s TATP Tutorial Code" data-url="http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p>A parte il nome esotico, volevo presentarvi <strong>Lua&#8217;s Totally Awesome Tutorial Pack</strong> xD</p>
<p>Un modo esagerato e divertente per dirvi che ho raccolto tutto il codice degli scorsi tutorial su Lua e C++ in un comodo file tar.gz. All&#8217;interno trovate anche l&#8217;ultimissima versione di LuaGrip.</p>
<p><a href="http://dl.dropbox.com/u/89889/LuaTutorialMegaPack_01.tar.gz">DOWNLOAD</a></p>
<p>Per prima cosa dovete installare LuaGrip. Per fare questo basta dare i comandi di rito:</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">mkdir build<br />
cd build<br />
cmake ..<br />
make<br />
sudo make install</div></div>
<p>A questo punto potete compilare ogni file nel tutorial con g++ aggiungendo i dovuti flag. Se non conoscete i flag vi basta aggiungere in coda:</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">`pkg-config --cflags libluagrip` `pkg-config --cflags lua5.1` `pkg-config --libs libluagrip` `pkg-config --libs lua5.1`</div></div>
<p>Non proprio una meraviglia di lettura ma dovrebbe fare decentemente il suo lavoro. <img src='http://davideaversa.it/slashcode/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  Magari date i comandi singolarmente e vi segnate i flag in modo da non dover recuperare questa stringa infinita di byte ogni volta che dovete compilare un programma con LuaGrip.</p>
<p>I tutorial funzionano anche su Windows ma non so come compilarli dato che non uso Windows da un lustro.</p>
<p>Fatemi sapere se ci sono problemi.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=735&amp;md5=8ffa3d8d59dc0fb5b3443a80be887e10" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/luas-tatp-tutorial-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluas-tatp-tutorial-code%2F&amp;language=it_IT&amp;category=text&amp;title=Lua%26%238217%3Bs+TATP+Tutorial+Code&amp;description=A+parte+il+nome+esotico%2C+volevo+presentarvi+Lua%26%238217%3Bs+Totally+Awesome+Tutorial+Pack+xD+Un+modo+esagerato+e+divertente+per+dirvi+che+ho+raccolto+tutto+il+codice+degli+scorsi+tutorial+su...&amp;tags=C%2Clua%2Ctutorial%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Lua/C++ : Programmazione Event-Driven</title>
		<link>http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 12:32:46 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[lua]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=733</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/"><img title="Lua/C++ : Programmazione Event-Driven" src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/full-moon-et-bike-ride-150x150.jpg" alt="Lua/C++ : Programmazione Event-Driven"  width="200" height="200" /></a></div><br/>Prima cosa. Così la programmazione event-driven? Risposta semplice: un paradigma di programmazione in cui parti di codice vengono avviare dal lancio di eventi. Risposta ancora più semplice (per gli esperti: perdonatemi la banalizzazione). Immaginate tre persone in una casa. Immaginate che queste persone, dotate di genitori nerd molto crudeli, si chiamino Stampa, AggiungiUno e, ovviamente, <a href='http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluac-programmazione-event-driven%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Lua/C++ : Programmazione Event-Driven" data-url="http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><a href="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/full-moon-et-bike-ride.jpg"><img src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/full-moon-et-bike-ride-150x150.jpg" alt="" title="full-moon-et-bike-ride" width="150" height="150" class="alignleft size-thumbnail wp-image-734" /></a></p>
<p>Prima cosa. Così la programmazione event-driven? Risposta semplice: un paradigma di programmazione in cui parti di codice vengono avviare dal lancio di <em>eventi</em>. Risposta ancora più semplice (per gli esperti: perdonatemi la banalizzazione). Immaginate tre persone in una casa. Immaginate che queste persone, dotate di genitori nerd molto crudeli, si chiamino Stampa, AggiungiUno e, ovviamente, Main. Main, il leader del gruppo, vuole contare tutte le macchine rosse che passano davanti la finestra.</p>
<p>Main ha due possibilità: andare a chiamare personalmente AggiungiUno per chiedergli di aumentare un contatore e Stampa per avere il risultato, oppure urlare &#8220;MACCHINA ROSSA&#8221; in modo tale che chi di dovere capisca che è passata una macchina rossa e aggiunga il contatore.</p>
<p>In questo scenario i due metodi sono pressocché equivalenti, ma supponiamo che Main non conosca il nome di chi è nella casa oppure che ad un certo punto AggiungiUno si faccia sostituire da IncrementaUno. In questo caso sarebbe impossibile <em>programmare</em> Main secondo il primo approccio mentre sarebbe banale programmare Main in modo da gridare MACCHINA ROSSA assumendo che ci sia qualcuno nella casa in grado di capire il significato di quel grido.</p>
<p>La programmazione event-driven consiste proprio nel gridare MACCHINA ROSSA. Ovviamente in programmazione non c&#8217;è il suono, sta a noi programmare il mezzo in cui gli eventi vengono propagati.</p>
<p>Senza entrare nel dettaglio vediamo come implementare i Lua e C++ un semplice meccanismo a eventi. Gli eventi saranno lanciati da C++ e verranno raccolti da una funzione Lua.</p>
<div class="codecolorer-container lua dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="lua codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">-- Esempio di programmazione Event-Driven</span><br />
<span style="color: #808080; font-style: italic;">-- in Lua.</span><br />
<br />
MACCHINA_ROSSA <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">1000</span><br />
STAMPA <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">2000</span><br />
<br />
numero_macchine_rosse <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">0</span><br />
<br />
RegisterEventHandler<span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;EventHandler&quot;</span><span style="color: #66cc66;">&#41;</span><br />
<br />
<span style="color: #aa9900; font-weight: bold;">function</span> EventHandler<span style="color: #66cc66;">&#40;</span>id<span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">if</span> id <span style="color: #66cc66;">==</span> MACCHINA_ROSSA <span style="color: #aa9900; font-weight: bold;">then</span><br />
&nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Macchine +1&quot;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; numero_macchine_rosse <span style="color: #66cc66;">=</span> numero_macchine_rosse <span style="color: #66cc66;">+</span> <span style="color: #cc66cc;">1</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">elseif</span> id <span style="color: #66cc66;">==</span> STAMPA <span style="color: #aa9900; font-weight: bold;">then</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #0000aa;">string.format</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;%s%d&quot;</span><span style="color: #66cc66;">,</span> <span style="color: #ff6666;">&quot;Num. Macchine: &quot;</span><span style="color: #66cc66;">,</span> numero_macchine_rosse<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #aa9900; font-weight: bold;">end</span><br />
<span style="color: #aa9900; font-weight: bold;">end</span></div></div>
<p>Cominciamo con lo script Lua.</p>
<p>Le prime due righe associano solo l&#8217;indice dell&#8217;evento che vogliamo ad una variabile mnemonica. Nulla di particolare, serve solo a rendere il codice più leggibile e chiaro.</p>
<p>La funzione <code class="codecolorer text dawn"><span class="text">RegisterEventHandler</span></code> è importante. È una funzione LuaGlue, ovvero una funzione implementata in C++. Questa funzione comunica alla parte C++ quale è il nome della funzione che gestisce gli eventi. La funzione non è in teoria strettamente necessaria, si potrebbe, ad esempio, scrivere direttamente nel codice C++ che la funzione che gestisce gli eventi è EventHandler. Tuttavia in questo modo renderemmo il codice C++ dipendente dal codice Lua: se cambiamo il nome della funzione o se vogliamo cambiarla in run-time dobbiamo riscrivere anche il codice C++. Usando  <code class="codecolorer text dawn"><span class="text">RegisterEventHandler</span></code> invece le due cose sono completamente disaccoppiate.</p>
<p>Vediamo ora la funzione principe. <code class="codecolorer text dawn"><span class="text">EventHandler</span></code> è il mezzo tramite cui gli eventi si propagano ed ha un comportamento molto semplice: riceve in ingresso l&#8217;id dell&#8217;evento e lo smista verso la funzione idonea. Nel nostro caso, poiché le funzioni sono piuttosto semplici sono scritte direttamente in <code class="codecolorer text dawn"><span class="text">EventHandler</span></code>.</p>
<p>Ora vediamo il listato C++.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include&lt;iostream&gt;</span><br />
<span style="color: #339900;">#include&lt;luagrip.hpp&gt;</span><br />
<span style="color: #339900;">#include&lt;string&gt;</span><br />
<br />
<span style="color: #339900;">#define MACCHINA_ROSSA 1000</span><br />
<span style="color: #339900;">#define STAMPA 2000</span><br />
<br />
std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> strEventHandler <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;&quot;</span><span style="color: #008080;">;</span><br />
LuaGrip<span style="color: #000040;">*</span> pLua<span style="color: #008080;">;</span><br />
<br />
LuaGlue _RegisterEventHandler<span style="color: #008000;">&#40;</span>lua_State <span style="color: #000040;">*</span>L<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; strEventHandler <span style="color: #000080;">=</span> pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetStringArgument<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #FF0000;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">void</span> FireEvent<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> id<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>strEventHandler <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">char</span> buf<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">254</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000dd;">sprintf</span><span style="color: #008000;">&#40;</span>buf, <span style="color: #FF0000;">&quot;%s(%d)&quot;</span>, strEventHandler.<span style="color: #007788;">c_str</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, id<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunString<span style="color: #008000;">&#40;</span>buf<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; pLua <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> LuaGrip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>AddFunction<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;RegisterEventHandler&quot;</span>,_RegisterEventHandler<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunScript<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;event.lua&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// Carica il modulo Lua.</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; FireEvent<span style="color: #008000;">&#40;</span>MACCHINA_ROSSA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; FireEvent<span style="color: #008000;">&#40;</span>MACCHINA_ROSSA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; FireEvent<span style="color: #008000;">&#40;</span>STAMPA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; FireEvent<span style="color: #008000;">&#40;</span>MACCHINA_ROSSA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; FireEvent<span style="color: #008000;">&#40;</span>STAMPA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000dd;">delete</span> pLua<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Il codice è composto da tre funzioni.</p>
<p>La prima è <code class="codecolorer text dawn"><span class="text">_RegisterEventHandler</span></code>. Abbiamo già parlato di questa funzione che si limita a ricevere il nome della funzione incaricata di gestire gli eventi e di memorizzarlo in una variabile globale.</p>
<p>La seconda è <code class="codecolorer text dawn"><span class="text">FireEvent</span></code>. Come possiamo intuire dal nome questa funzione lancia gli eventi (nel nostro esempio corrisponde all&#8217;azione di gridare). In che modo? Ci sono molti modi diversi, il più semplice dei quali consiste nel creare una stringa che corrisponde ad una chiamata di funzione Lua e poi eseguirla nel solito modo.</p>
<p>Infine la funzione main inizializza Lua e lancia gli eventi. La sequenza descritta in main da luogo al seguente output:</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Macchine +1<br />
Macchine +1<br />
Num. Macchine: 2<br />
Macchine +1<br />
Num. Macchine: 3</div></div>
<p>Questa struttura è la base del meccanismo event-driven. Ovviamente la struttura può essere ulteriormente complicata, ad esempio permettendo l&#8217;uso di eventi con argomenti (ad esempio un evento <code class="codecolorer text dawn"><span class="text">IncrementaN</span></code>). </p>
<p>La prossima volta vorrei farvi vedere invece come sfruttare Lua per il salvataggio e il caricamento dei dati. </p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=733&amp;md5=a213e5c477e39e4ce8617bb827c1711b" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/luac-programmazione-event-driven/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluac-programmazione-event-driven%2F&amp;language=it_IT&amp;category=text&amp;title=Lua%2FC%2B%2B+%3A+Programmazione+Event-Driven&amp;description=Prima+cosa.+Cos%C3%AC+la+programmazione+event-driven%3F+Risposta+semplice%3A+un+paradigma+di+programmazione+in+cui+parti+di+codice+vengono+avviare+dal+lancio+di+eventi.+Risposta+ancora+pi%C3%B9+semplice+%28per+gli+esperti%3A...&amp;tags=C%2Clua%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Lua/C++ : Passaggio Di Parametri</title>
		<link>http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/#comments</comments>
		<pubDate>Thu, 09 Jun 2011 06:45:55 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[lua]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=730</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/"><img title="Lua/C++ : Passaggio Di Parametri" src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/593px-Aldrin_Apollo_11_original-150x150.jpg" alt="Lua/C++ : Passaggio Di Parametri"  width="200" height="200" /></a></div><br/>Abbiamo visto negli articoli precedenti come utilizzare funzioni C++ all&#8217;interno dei script Lua (e viceversa). Ci eravamo però dimenticati di dire come fare a passare dati sottoforma di parametri fra Lua e C++. Ora è giunto il momento di colmare questa lacuna. Il passaggio di parametri fra funzioni Lua e C++ è, come potete immaginare, <a href='http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluac-passaggio-di-parametri%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Lua/C++ : Passaggio Di Parametri" data-url="http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><a href="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/593px-Aldrin_Apollo_11_original.jpg"><img src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/593px-Aldrin_Apollo_11_original-150x150.jpg" alt="Aldrin Apollo 11" title="Aldrin Apollo 11" width="150" height="150" class="aligncenter size-thumbnail wp-image-731" /></a></p>
<p>Abbiamo visto negli articoli precedenti come utilizzare funzioni C++ all&#8217;interno dei script Lua (e viceversa). Ci eravamo però dimenticati di dire come fare a passare dati sottoforma di parametri fra Lua e C++. Ora è giunto il momento di colmare questa lacuna.</p>
<p>Il passaggio di parametri fra funzioni Lua e C++ è, come potete immaginare, un aspetto fondamentale della programmazione mista Lua/C++. Tuttavia, nonostante la procedura non sia delle più intuitive, è estremamente semplice. Ma partiamo da un esempio, consideriamo il seguente script Lua.</p>
<div class="codecolorer-container lua dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="lua codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">-- Questo è un esempio di script Lua che </span><br />
<span style="color: #808080; font-style: italic;">-- utilizza al suo interno una funzione C++.</span><br />
<br />
<span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Fattoriale di 5!&quot;</span><span style="color: #66cc66;">&#41;</span><br />
<span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Implementato in C++ con amore!&quot;</span><span style="color: #66cc66;">&#41;</span><br />
<span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span>Factorial<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></div></div>
<p>Un caso d&#8217;uso dei più banali consiste nell&#8217;usare all&#8217;interno di uno script Lua funzioni C++ per le operazioni CPU-intensive. Possiamo trovare un esempio spicciolo nel listato Lua precedente. La funzione <code class="codecolorer text dawn"><span class="text">Factorial</span></code> per il calcolo del fattoriale è notoriamente una funzione che necessita di una buona velocità. Così, invece di implementarla in Lua useremo una funzione C++. Vediamo quindi il codice C++.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">LuaGrip<span style="color: #000040;">*</span> pLua<span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">int</span> factorial_recursive<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> n<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>n<span style="color: #000080;">==</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> n <span style="color: #000040;">*</span> factorial_recursive<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
LuaGlue _Factorial<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">struct</span> lua_State <span style="color: #000040;">*</span>pLuaState<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/* Ricaviamo i parametri della funzione.<br />
&nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp;* La funzione Lua agganciata a questa funzione C++<br />
&nbsp; &nbsp; &nbsp;* ha la seguente struttura:<br />
&nbsp; &nbsp; &nbsp;*<br />
&nbsp; &nbsp; &nbsp;* &nbsp; &nbsp; int Factorial(int n)<br />
&nbsp; &nbsp; &nbsp;*<br />
&nbsp; &nbsp; &nbsp;* Dobbiamo quindi recuperare il primo int.<br />
&nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">double</span> n<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;n <span style="color: #000080;">=</span> pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetNumberArgument<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #ff0000; font-style: italic;">/* Calcoliamo il fattoriale */</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">int</span> res <span style="color: #000080;">=</span> factorial_recursive<span style="color: #008000;">&#40;</span>n<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #ff0000; font-style: italic;">/* Restituiamo il valore di ritorno */</span><br />
&nbsp; &nbsp; &nbsp;pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>PushNumber<span style="color: #008000;">&#40;</span>res<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp;<br />
&nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">return</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>La funzione <code class="codecolorer text dawn"><span class="text">_Factorial</span></code> è la classica funzione LuaGlue. La domanda viene spontanea: come fare a passare il valore 5 alla funzione Factorial? E come fare a restituire il valore finale? Andiamo per passi:</p>
<p>La prima cosa che facciamo nella funzione <code class="codecolorer text dawn"><span class="text">_Factorial</span></code> è proprio recuperare il parametro 5. Facciamo questo tramite la funzione LuaGrip <code class="codecolorer text dawn"><span class="text">double GetNumberArgument(int argnum)</span></code>. La funzione prende in ingresso il numero del parametro da recuperare, nel nostro caso abbiamo bisogno del primo parametro e quindi usiamo semplicemente il numero 1. Come valore di ritorno la funzione restituisce un double.</p>
<p>A questo punto passiamo il valore recuperato ad una funzione &#8220;tradizionale&#8221; <code class="codecolorer text dawn"><span class="text">factorial_recursive</span></code> che calcola il valore del fattoriale nel modo &#8220;classico&#8221;.</p>
<p>Infine, il valore di ritorno viene restituito a Lua grazie alla funzione LuaGrip <code class="codecolorer text dawn"><span class="text">void PushNumber(res)</span></code>.</p>
<p>Mi raccomando <strong>non dimenticate di ritornare un 1 alla fine</strong> altrimenti Lua interpreterà il mancato valore di ritorno come un errore nella funzione.</p>
<p>A questo punto scriviamo il main che, in questo caso, non farà altro che agganciare la funzione Factorial a Lua e lanciare lo script.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; pLua <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> LuaGrip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>AddFunction<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Factorial&quot;</span>,_Factorial<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunScript<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;fac.lua&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000dd;">delete</span> pLua<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>A questo punto l&#8217;integrazione è completa! Non c&#8217;è molto altro da sapere <img src='http://davideaversa.it/slashcode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Tuttavia continuerò a presentare esempi. Nel prossimo articolo su Lua/C++ ho intenzione di parlare su come utilizzare Lua per la programmazione event-driven.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=730&amp;md5=d53212be396d32a9a0590d33d4b30ec2" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/luac-passaggio-di-parametri/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fluac-passaggio-di-parametri%2F&amp;language=it_IT&amp;category=text&amp;title=Lua%2FC%2B%2B+%3A+Passaggio+Di+Parametri&amp;description=Abbiamo+visto+negli+articoli+precedenti+come+utilizzare+funzioni+C%2B%2B+all%26%238217%3Binterno+dei+script+Lua+%28e+viceversa%29.+Ci+eravamo+per%C3%B2+dimenticati+di+dire+come+fare+a+passare+dati+sottoforma+di+parametri+fra...&amp;tags=C%2Clua%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Approfondiamo Lua</title>
		<link>http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 17:10:43 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=726</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/"><img title="Approfondiamo Lua" src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Full_Moon_Space_Art-150x150.jpg" alt="Approfondiamo Lua"  width="200" height="200" /></a></div><br/>Poiché l&#8217;argomento Lua e C++ è di notevole interesse per me ed ha suscitato un discreto numero di contatti mi sento in dovere di approfondirlo. La cosa necessiterebbe di un mare di tempo e spazio in quanto si potrebbero scrivere libri e libri sull&#8217;argomento (e infatti ce ne sono migliaia) ma cercherò di concentrarmi sugli <a href='http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fapprofondiamo-lua%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Approfondiamo Lua" data-url="http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><a href="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Full_Moon_Space_Art.jpg"><img src="http://davideaversa.it/slashcode/wp-content/uploads/2011/06/Full_Moon_Space_Art-150x150.jpg" alt="Full Moon Space Art" title="Full Moon Space Art" width="150" height="150" class="aligncenter size-thumbnail wp-image-727" /></a></p>
<p>Poiché l&#8217;argomento Lua e C++ è di notevole interesse per me ed ha suscitato un discreto numero di contatti mi sento in dovere di approfondirlo. La cosa necessiterebbe di un mare di tempo e spazio in quanto si potrebbero scrivere libri e libri sull&#8217;argomento (e infatti<a href="http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&#038;field-keywords=lua&#038;x=0&#038;y=0"> ce ne sono migliaia</a>) ma cercherò di concentrarmi sugli aspetti pratici e implementativi.</p>
<p>Per ogni esempio che farò ora e per i secoli a venire farò sempre riferimento alla mia <em>libreria</em> <strong>LuaGrip</strong> (che potete scaricare <a href="http://dl.dropbox.com/u/89889/libluagrip-1.1.tar.gz">qui</a>). Questa libreria ha lo scopo di nascondere e avvolgere il collegamento di basso livello con la libreria nativa di Lua. Ho fatto questo per due motivi:</p>
<ul>
<li>Semplificare e abbreviare le operazioni ripetitive del collegamento c++/lua come ad esempio la creazione dell&#8217;ambiente lua e la sua distruzione.</li>
<li>La libreria di Lua è scritta in C e la sua integrazione in C++ richiede un paio di accortezze che magari risulterebbero di difficile comprensione a chi non è espertissimo. Usando LuaGrip potete fregarvene del tutto e potete utilizzarlo tranquillamente anche se siete apprendisti.</li>
</ul>
<p>La libreria è direttamente ispirata (dico ispirata per dire che le API sono copiate pari pari) ad una libreria descritta nel libro <em>&#8220;Game Developement with Lua&#8221;</em> di <em>Paul Schuytema</em> e <em>Mark Manyen</em>. Ho dovuto però reimplementare tutto per rendere l&#8217;interfaccia il più generica possibile e per aggiornare il codice alla nuova versione di lua (5.1).</p>
<p>Detto questo, la prima cosa da fare è studiarci per bene il programma di esempio che è incluso nel pacchetto:</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &lt;stdio.h&gt;</span><br />
<span style="color: #339900;">#include &lt;string.h&gt;</span><br />
<span style="color: #339900;">#include &quot;luagrip.hpp&quot;</span></div></div>
<p>Per prima cosa che vediamo sono i consueti <em>include</em>.  Fin qui non c&#8217;è nulla di particolare.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">LuaGlue _Version<span style="color: #008000;">&#40;</span>lua_State <span style="color: #000040;">*</span>L<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000dd;">puts</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;This is Version 2.0 of the Console Program&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>La prima funzione che troviamo è la funzione <code class="codecolorer text dawn"><span class="text">_Version</span></code>. Questa funzione è una funzione <em>LuaGlue</em> ovvero una funzione implementata in C++ che sarà richiamabile da uno script Lua. La funzione ha i seguenti particolari:</p>
<ul>
<li>Il valore di ritorno è <code class="codecolorer text dawn"><span class="text">LuaGlue</span></code>. Consideratelo semplicemente un valore int.</li>
<li>Il nome comincia con un <em>underscore</em> (_). Questa è solo una convenzione stilistica.</li>
<li>Come unico parametro in ingresso abbiamo un puntatore a <code class="codecolorer text dawn"><span class="text">lua_State</span></code>.</li>
</ul>
<p>Tutto questo sembra estremamente limitante ma così non è. Vedremo poi come sia possibile sfruttare il puntatore allo stato (o semplicemente la classe LuaGrip) per avere in ingresso qualsiasi parametro e restituire qualunque valore.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">char</span> gpCommandBuffer<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">254</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>GetCommand<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Ready&gt; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">fgets</span><span style="color: #008000;">&#40;</span>gpCommandBuffer,<span style="color: #0000dd;">254</span>,<span style="color: #0000ff;">stdin</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Questa è una semplice funzione ausiliaria, non ha nessun collegamento con lua. Questa funzione non fa altro che leggere una stringa dalla shell e memorizzarla nel buffer <code class="codecolorer text dawn"><span class="text">gpCommandBuffer</span></code>.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; LuaGrip <span style="color: #000040;">*</span>pLua <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> LuaGrip<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>AddFunction<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Version&quot;</span>,_Version<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunScript<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;hello.lua&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pCommand <span style="color: #000080;">=</span> GetCommand<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">while</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">strcmp</span><span style="color: #008000;">&#40;</span>pCommand, <span style="color: #FF0000;">&quot;QUIT<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunString<span style="color: #008000;">&#40;</span>pCommand<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;ERROR:%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>,pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetErrorString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; pCommand <span style="color: #000080;">=</span> GetCommand<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000dd;">delete</span> pLua<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Ora veniamo al sodo: la funzione <code class="codecolorer text dawn"><span class="text">main</span></code>. La prima cosa che facciamo è creare un istanza della classe LuaGrip che inizializza la macchina virtuale di Lua.</p>
<p>Subito dopo agganciamo la funzione <code class="codecolorer text dawn"><span class="text">_Version</span></code> all&#8217;interprete Lua. In pratica diciamo alla macchina virtuale di Lua di agganciare la funzione Lua <code class="codecolorer text dawn"><span class="text">Version</span></code> alla funzione C <code class="codecolorer text dawn"><span class="text">_Version</span></code>. Da questo momento in poi possiamo usare la funzione <code class="codecolorer text dawn"><span class="text">Version()</span></code> all&#8217;interno di uno script Lua come se fosse un qualsiasi altro comando Lua.</p>
<p>Subito dopo eseguiamo lo script <code class="codecolorer text dawn"><span class="text">hello.lua</span></code>, script che non fa altro che stampare a schermo una breve introduzione per la nostra console. </p>
<p>A questo punto inizia il ciclo della shell. Leggiamo i comandi inviati dall&#8217;utente fino a quando non viene digitato il comando QUIT. I comandi di nostro interesse sono:</p>
<ul>
<li><code class="codecolorer cpp dawn"><span class="cpp">pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunString<span style="color: #008000;">&#40;</span>pCommand<span style="color: #008000;">&#41;</span></span></code> &#8211; Analogamente al comando <code class="codecolorer text dawn"><span class="text">RunScript</span></code>, il quale esegue uno script contenuto in un file, questo comando esegue comandi Lua contenuti in una stringa.</li>
<li><code class="codecolorer cpp dawn"><span class="cpp">pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetErrorString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span></span></code> &#8211; Questo comando restituisce la stringa di errore generata dall&#8217;interprete.</li>
</ul>
<p>Alla fine non ci resta che eliminare l&#8217;istanza di LuaGrip per terminare la macchina virtuale.</p>
<p>Ora siamo pronti a vedere come passare valori e parametri fra C++ e Lua. Ma questo ve lo racconto un&#8217;altra volta.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=726&amp;md5=a83d61702c1aa3eee07df9afe2752d7b" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/approfondiamo-lua/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Fapprofondiamo-lua%2F&amp;language=it_IT&amp;category=text&amp;title=Approfondiamo+Lua&amp;description=Poich%C3%A9+l%26%238217%3Bargomento+Lua+e+C%2B%2B+%C3%A8+di+notevole+interesse+per+me+ed+ha+suscitato+un+discreto+numero+di+contatti+mi+sento+in+dovere+di+approfondirlo.+La+cosa+necessiterebbe+di+un...&amp;tags=C%2Clua%2Cscript%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Lua e C++</title>
		<link>http://davideaversa.it/slashcode/2011/06/lua-e-c/</link>
		<comments>http://davideaversa.it/slashcode/2011/06/lua-e-c/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 14:32:38 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=725</guid>
		<description><![CDATA[Lua (parola portoghese per <em>luna</em>) è un linguaggio di scripting dinamico, riflessivo  e procedurale di origine brasiliana usato massivamente nell'industria dei videogiochi.
]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Flua-e-c%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2011/06/lua-e-c/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Lua e C++" data-url="http://davideaversa.it/slashcode/2011/06/lua-e-c/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><strong>Cos&#8217;è Lua?</strong></p>
<p>Lua (parola portoghese per <em>luna</em>) è un linguaggio di scripting dinamico, riflessivo  e procedurale di origine brasiliana usato massivamente nell&#8217;industria dei videogiochi.</p>
<p><strong>Cosa ci fa l&#8217;industria dei videogame con Lua? Non usano il c++?</strong></p>
<p>Si. Programmi con altissime richieste prestazionali come i videogiochi non possono fare a meno di utilizzare linguaggi compilati di medio-basso livello come il c++. Tuttavia programmare in c++ è sicuramente più scomodo che programmare in un linguaggio di alto livello e, inoltre, non tutte le parti di un software necessitano della stessa ferrea richiesta di performance. Sarebbe come voler costruire una casa resistente intagliandola in un mastodontico blocco di marmo. <img src='http://davideaversa.it/slashcode/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  La prassi consiste quindi nello scrivere grossi <em>mattoni</em> in C++ puro e di legarli insieme con una <em>calce</em> fatta con un linguaggio di scripting. </p>
<p>Nell&#8217;industria dei videogiochi da molto tempo si utilizza una calce fatta con Lua.</p>
<p><strong>Lua? Perché usare un linguaggio che non ho mai sentito quando si può usare un linguaggio noto come Python, Ruby o altro?</strong></p>
<p>Nulla vi vieta di usarli. Tuttavia ci sono tre grandi motivi che rendono ancora Lua un <em>leader</em> nel suo campo. Primo, Lua nasce per essere integrato in codice compilato, integrazione che quindi risulta semplice ed efficace. Secondo, a differenza degli altri linguaggi di scripting Lua è decisamente <strong>spartano</strong>, non possiede nemmeno il paradigma a oggetti (che però può essere replicato in modo personalizzato usando le strutture dati native di Lua); questa essenzialità rende Lua performante. Terzo, e più importante, Lua è estremamente versatile per quanto riguarda il multithreading (permette, ad esempio, di avviare un interprete separato per ogni thread).</p>
<p>Detto questo potete comunque utilizzare nel vostro progetto qualunque linguaggio di scripting, ma almeno saprete cosa ha Lua in più o in meno (e potrete così fare una scelta consapevole).</p>
<p><strong>Figo! Come posso integrare Lua in un mio progetto?</strong></p>
<p>Ho scritto un wrapper in C++ per semplificare ulteriormente l&#8217;integrazione di Lua nel vostro progetto.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#ifndef H_LUAGRIP</span><br />
<span style="color: #339900;">#define H_LUAGRIP</span><br />
<br />
<span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #008000;">&#123;</span><br />
<span style="color: #339900;">#include &lt;lua.h&gt;</span><br />
<span style="color: #339900;">#include &lt;lualib.h&gt;</span><br />
<span style="color: #339900;">#include &lt;lauxlib.h&gt;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">struct</span> lua_State<span style="color: #008080;">;</span><br />
<br />
<span style="color: #339900;">#define LuaGlue extern &quot;C&quot; int</span><br />
<br />
<span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">typedef</span> <span style="color: #0000ff;">int</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>LuaFunctionType<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">struct</span> lua_State <span style="color: #000040;">*</span>pLuaState<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">class</span> LuaGrip<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Constructor.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; LuaGrip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">virtual</span> ~LuaGrip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Execute Lua script indicated by pFilename.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @param pFilename [in] Script's path.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @return false on error. true otherwise.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">bool</span> RunScript<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pFilename<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Execute one string.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @param pCommand [in] String representing a Lua command.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @return false on error. true otherwise.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span> <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">bool</span> RunString<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pCommand<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Get a string representing the last occurred error.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @return ...<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>GetErrorString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Link a C/C++ function to Lua interpeter.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @param pFunctionName [in] String of function name.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @param pfunction [in] Pointer to a function you are going to link.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* @return &nbsp;false on error. true otherwise.<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">bool</span> AddFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pFunctionName, LuaFunctionType pFunction<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>GetStringArgument<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> num, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pDefault<span style="color: #000080;">=</span><span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff0000; font-style: italic;">/**<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">double</span> GetNumberArgument<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> num, <span style="color: #0000ff;">double</span> dDefault<span style="color: #000080;">=</span><span style="color:#800080;">0.0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">void</span> PopLast<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">void</span> PushString<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pString<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">void</span> PushNumber<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> value<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; lua_State <span style="color: #000040;">*</span>m_State<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #339900;">#endif /* H_LUAGRIP */</span></div></div>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &quot;luagrip.hpp&quot;</span><br />
<span style="color: #339900;">#include &lt;string.h&gt;</span><br />
<br />
LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">LuaGrip</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State <span style="color: #000080;">=</span> luaL_newstate<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; luaL_openlibs<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
LuaGrip<span style="color: #008080;">::</span>~LuaGrip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; lua_close<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">bool</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">AddFunction</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pFunctionName, LuaFunctionType pFunction<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; lua_register<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State,pFunctionName,pFunction<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">bool</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">RunScript</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pFilename<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>luaL_loadfile<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, pFilename<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>lua_pcall<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, <span style="color: #0000dd;">0</span>, LUA_MULTRET, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">bool</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">RunString</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pCommand<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>luaL_loadbuffer<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, pCommand, <span style="color: #0000dd;">strlen</span><span style="color: #008000;">&#40;</span>pCommand<span style="color: #008000;">&#41;</span>, <span style="color: #FF0000;">&quot;line&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>lua_pcall<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">GetErrorString</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> lua_tostring<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">GetStringArgument</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> num, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pDefault<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> luaL_optstring<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, num, pDefault<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">double</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">GetNumberArgument</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> num, <span style="color: #0000ff;">double</span> dDefault<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> luaL_optnumber<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, num, dDefault<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">void</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">PushString</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pString<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; lua_pushstring<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, pString<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">void</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">PushNumber</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> value<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; lua_pushnumber<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State, value<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">void</span> LuaGrip<span style="color: #008080;">::</span><span style="color: #007788;">PopLast</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; lua_pop<span style="color: #008000;">&#40;</span>this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>m_State,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Sono due file (uno .hpp e l&#8217;altro .cpp) che vi basta aggiungere al vostro progetto ed utilizzarli come una classe qualsiasi.</p>
<p><strong>Ottimo! Un esempio?</strong></p>
<p>Ovviamente. Questa è una piccola &#8220;shell&#8221; per Lua.</p>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339900;">#include &lt;stdio.h&gt;</span><br />
<span style="color: #339900;">#include &lt;string.h&gt;</span><br />
<span style="color: #339900;">#include &quot;luagrip.hpp&quot;</span><br />
<br />
<span style="color: #0000ff;">extern</span> <span style="color: #FF0000;">&quot;C&quot;</span> <span style="color: #0000ff;">int</span> _Version<span style="color: #008000;">&#40;</span>lua_State <span style="color: #000040;">*</span>L<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000dd;">puts</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;This is Version 2.0 of the Console Program&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">char</span> gpCommandBuffer<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">254</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>GetCommand<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Ready&gt; &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">fgets</span><span style="color: #008000;">&#40;</span>gpCommandBuffer,<span style="color: #0000dd;">254</span>,<span style="color: #0000ff;">stdin</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">//return gets(gpCommandBuffer);</span><br />
<span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; LuaGrip <span style="color: #000040;">*</span>pLua <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> LuaGrip<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>AddFunction<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Version&quot;</span>,_Version<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunScript<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;hello.lua&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pCommand <span style="color: #000080;">=</span> GetCommand<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">while</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">strcmp</span><span style="color: #008000;">&#40;</span>pCommand, <span style="color: #FF0000;">&quot;QUIT<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>RunString<span style="color: #008000;">&#40;</span>pCommand<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;ERROR:%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>,pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>GetErrorString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pLua<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>PopLast<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; pCommand <span style="color: #000080;">=</span> GetCommand<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #0000dd;">delete</span> pLua<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
<p>Hello.lua non è altro che un &#8220;Hello World&#8221; scritto in Lua: <code class="codecolorer lua dawn"><span class="lua"><span style="color: #0000aa;">print</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff6666;">&quot;Hello World!&quot;</span><span style="color: #66cc66;">&#41;</span></span></code></p>
<p>Se volete vi darò qualche ulteriore dettaglio sull&#8217;uso di Lua in un prossimo articolo. Fatemi sapere.</p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=725&amp;md5=686985352089f2f4dd85d429c767d4f4" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2011/06/lua-e-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2011%2F06%2Flua-e-c%2F&amp;language=it_IT&amp;category=text&amp;title=Lua+e+C%2B%2B&amp;description=Cos%26%238217%3B%C3%A8+Lua%3F+Lua+%28parola+portoghese+per+luna%29+%C3%A8+un+linguaggio+di+scripting+dinamico%2C+riflessivo+e+procedurale+di+origine+brasiliana+usato+massivamente+nell%26%238217%3Bindustria+dei+videogiochi.+Cosa+ci+fa+l%26%238217%3Bindustria+dei+videogame...&amp;tags=C%2Clua%2Cscript%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Qt: Segnali e Slot</title>
		<link>http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/</link>
		<comments>http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 22:32:19 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Varie]]></category>
		<category><![CDATA[qt]]></category>
		<category><![CDATA[signal]]></category>
		<category><![CDATA[slot]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=614</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/"><img title="Qt: Segnali e Slot" src="http://davideaversa.it/slashcode/wp-content/uploads/2010/06/bat-signal-150x150.jpg" alt="Qt: Segnali e Slot"  width="200" height="200" /></a></div><br/>Molti conosceranno sicuramente le Librerie QT: esse sono infatti il principale tool-kit grafico della suite desktop KDE nonché di molti altre applicazioni e sistemi embedded. In quanto tali, quando si parla di Qt, molti pensano ad esse solamente come mere librerie grafiche, in realtà, tali librerie vanno ben oltre la semplice gestione e visualizzazione di <a href='http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2010%2F06%2Fqt-segnali-e-slot%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="Qt: Segnali e Slot" data-url="http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><img class="alignleft size-thumbnail wp-image-615" title="bat signal" src="http://davideaversa.it/slashcode/wp-content/uploads/2010/06/bat-signal-150x150.jpg" alt="" width="150" height="150" /></p>
<div style="text-align: justify;">Molti conosceranno sicuramente le Librerie QT: esse sono infatti il principale tool-kit grafico della suite desktop KDE nonché di molti altre applicazioni e sistemi embedded. In quanto tali, quando si parla di Qt, molti pensano ad esse solamente come mere librerie grafiche, in realtà, tali librerie vanno ben oltre la semplice gestione e visualizzazione di finestre e widget: esse sono infatti una libreria che racchiude un gran numero di layer che semplificano lo sviluppo software in generale. In questo breve articolo infatti mostrerò uno dei tanti modi in cui l&#8217;uso delle librerie può Qt semplificare la vita agli sviluppatori: il meccanismo Meta-Object System (<em>moc</em>) e l&#8217;accoppiata <strong>signals</strong> e <strong>slots</strong>.</div>
<div style="text-align: justify;">Segnali (<em>signals</em>) e slot (<em>slots) </em>sono due elementi fondamentali della programmazione con le Qt. Essi permettono di legare insieme due oggetti senza che nessuno dei due sappia nulla dell&#8217;altro. È possibile, ad esempio, costruire due classi<em> </em>A e B e fare in modo che ad un evento di A corrisponda un azione di B e viceversa senza doversi minimamente preoccupare di inserire in A riferimenti di B (e rispettivamente in B riferimenti ad A).</div>
<div style="text-align: justify;">Un segnale è infatti un avviso emesso da un oggetto al verificarsi di determinate condizioni. Ad ogni segnale è collegato uno <em>slot</em> che non è nulla di diverso da una comune funzione C/C++: non appena è emesso il segnale X viene automaticamente eseguita la funzione Y.</div>
<div style="text-align: justify;">Per collegare un segnale ad uno slot si usa il comando</div>
<p><code class="codecolorer cpp dawn"><span class="cpp">connect<span style="color: #008000;">&#40;</span>sendre, SIGNAL<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">signal</span><span style="color: #008000;">&#41;</span>, receiver, SLOT<span style="color: #008000;">&#40;</span>slot<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></span></code></p>
<div style="text-align: justify;">dove <code class="codecolorer text dawn"><span class="text">sender</span></code> e <code class="codecolorer text dawn"><span class="text">receiver</span></code> sono puntatori a due oggetti (oggetti &#8220;qt&#8221; per la precisione) e <code class="codecolorer text dawn"><span class="text">signal</span></code> e <code class="codecolorer text dawn"><span class="text">slot</span></code> non sono altro che dichiarazioni di funzioni senza il nome dei parametri. Possiamo avere varie forme di connessioni:</div>
<div style="text-align: justify;">
<ul>
<li><strong>PIÙ SEGNALI COLLEGATI AD UN SOLO SLOT. </strong>In questo caso la stessa funzione viene lanciata in corrispondenza di due o più segnali differenti.</li>
<li><strong>UN SOLO SEGNALE COLLEGATO A PIÙ SLOT</strong><em><strong>. </strong></em>Viceversa, in questo caso, l&#8217;arrivo di un segnale avvia l&#8217;esecuzione di più funzioni. Tali funzioni vengono eseguite una dopo l&#8217;altra in un ordine indefinito (fate quindi molta attenzione alla sincronizzazione di tali funzioni).</li>
<li><strong>UN SEGNALE COLLEGATO AD UN SEGNALE.</strong> In questo caso l&#8217;arrivo di un segnale causa semplicemente il lancio di un nuovo segnale (che può essere la propagazione del primo o un segnale del tutto diverso).</li>
</ul>
<p>&#8220;Fantastico!&#8221; direte voi, ma cosa è necessario per poter usufruire di tale meraviglia? La cosa è ancora più semplice. Il primo requisito è che sia gli oggetti che lanciano e ricevono segnali sia quelli che definiscono gli slot  ereditino dalla classe <strong>QObject </strong>e definiscano al loro interno la macro <strong>Q_OBJECT</strong>. Secondo, quando connettiamo un segnale ad uno slot dobbiamo assicurarci che <strong>contengano lo stesso numero di parametri, dello stesso tipo e nello stesso ordine</strong>. Se le nostre classi rispondono a questi due requisiti siamo pronti ad utilizzare segnali e slot.</p>
<div style="text-align: justify;">Questo meccanismo è usato massicciamente nello sviluppo di applicazioni grafiche in Qt, tuttavia possiamo vedere dall&#8217;esempio seguente come esso possa essere applicato in classi che non hanno nulla a che vedere con il lato &#8220;grafico&#8221; delle Qt.</div>
<pre>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">class</span> Impiegato <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> QObject <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; Q_OBJECT<br />
&nbsp; &nbsp; <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; Impiegato<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> miosalario <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">int</span> salario<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> miosalario<span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">public</span> slots<span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">void</span> setSalario<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nuovo<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; signals<span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">void</span> salarioCambiato<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nuovo<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">int</span> miosalario<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">void</span> Impiegato<span style="color: #008080;">::</span><span style="color: #007788;">setSalario</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> nuovo<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>nuovo <span style="color: #000040;">!</span><span style="color: #000080;">=</span> miosalario<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; miosalario <span style="color: #000080;">=</span> nuovo<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; emit salarioCambiato<span style="color: #008000;">&#40;</span>miosalario<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span></div></div>
</pre>
<div style="text-align: justify;">Da questo stralcio di codice possiamo ricavare due osservazioni interessanti. La prima è che le funzioni <em>slot</em> sono del tutto identiche a classiche funzioni C++ e questo significa che possono tranquillamente essere invocate nel modo tradizionale. Il secondo punto è l&#8217;introduzione di alcune nuove parole chiave come <em>signals, slots </em>e <em>emit</em>. Queste parole chiave in realtà non sono altro che macro definite nella libreria Qt ma che svolgono un ruolo molto importante nel Meta-Object System.</div>
<div style="text-align: justify;">Un altra cosa che è bene precisare è l&#8217;implementazione di <em>setSalario:</em> essa è infatti progettata in modo tale da cambiare solamente se <em>nuovo</em> è diverso da <em>miosalario </em>in modo tale da evitare che si cada in un ciclo infinito in caso di connessione ciclica (ad esempio connettere il segnale salarioCambiato ad un istanza di Impiegato).</div>
</div>
<div style="text-align: justify;">L&#8217;uso di questo meccanismo crea però un anello in più nella fase di compilazione. Per assicurare che il processo <em>moc</em> vada a buon fine è necessario generare il file di compilazione (<em>makefile</em>) tramita un applicazione ad-hoc: <strong>qmake</strong>. L&#8217;uso di qmake è eccessivamente semplice quindi non approfondirò l&#8217;uso di questo tool.</div>
<div style="text-align: justify;"></div>
<div style="text-align: justify;">A questo punto avete a disposizione uno strumento meravigliosamente efficiente per la comunicazione fra oggetti della vostra applicazione, sia essa con interfaccia grafica sia senza. Non vi resta che approfondire questa tecnologia con qualche manciata di tutorial.</div>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=614&amp;md5=6e22f23276641b5f410e0d43e2fbf99d" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2010/06/qt-segnali-e-slot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2010%2F06%2Fqt-segnali-e-slot%2F&amp;language=it_IT&amp;category=text&amp;title=Qt%3A+Segnali+e+Slot&amp;description=Molti+conosceranno+sicuramente+le+Librerie+QT%3A+esse+sono+infatti+il+principale+tool-kit+grafico+della+suite+desktop+KDE+nonch%C3%A9+di+molti+altre+applicazioni+e+sistemi+embedded.+In+quanto+tali%2C+quando+si...&amp;tags=qt%2Csignal%2Cslot%2Cblog" type="text/html" />
	</item>
		<item>
		<title>C++ e le classi template</title>
		<link>http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/</link>
		<comments>http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/#comments</comments>
		<pubDate>Tue, 25 May 2010 17:15:13 +0000</pubDate>
		<dc:creator>THeK3nger</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://davideaversa.it/slashcode/?p=586</guid>
		<description><![CDATA[<div><a href="http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/"><img title="C++ e le classi template" src="http://davideaversa.it/slashcode/wp-content/uploads/2010/05/patchwork3-150x150.jpg" alt="C++ e le classi template"  width="200" height="200" /></a></div><br/>In e C/C++ si ha la convenzione di suddividere il codice all&#8217;interno di due file: i file .h per le dichiarazioni e .cpp o .c. Le motivazioni di questa scelta, in realtà, vanno oltre il semplice vezzo stilistico. Tale suddivisione permette infatti una profonda modularità del software e una rudimentale forma di information-hiding. I vari moduli <a href='http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/' class='excerpt-more'>[...]</a>]]></description>
			<content:encoded><![CDATA[<div style="height:33px;" class="really_simple_share robots-nocontent snap_nopreview"><div class="really_simple_share_facebook_like" style="width:100px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2010%2F05%2Fc-e-le-classi-template%2F&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;send=false&amp;height=27" 
						scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:27px;" allowTransparency="true"></iframe></div><div class="really_simple_share_google1" style="width:90px;"><div class="g-plusone" data-size="medium" data-href="http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/" ></div></div><div class="really_simple_share_twitter" style="width:110px;"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" 
						data-text="C++ e le classi template" data-url="http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/" 
						data-via=""  ></a></div></div>
		<div style="clear:both;"></div><p><img class="alignleft size-thumbnail wp-image-587" title="Patchwork" src="http://davideaversa.it/slashcode/wp-content/uploads/2010/05/patchwork3-150x150.jpg" alt="" width="150" height="150" />In e C/C++ si ha la convenzione di suddividere il codice all&#8217;interno di due file: i file <strong>.h</strong> per le dichiarazioni e <strong>.cpp</strong> o <strong>.c. </strong>Le motivazioni di questa scelta, in realtà, vanno oltre il semplice vezzo stilistico. Tale suddivisione permette infatti una profonda modularità del software e una rudimentale forma di information-hiding. I vari moduli (cpp) quando richiamano un altro modulo (tramite <em>include</em>) vengono a conoscenza solamente delle dichiarazioni delle funzioni e mai della loro implementazione. Implementazione che, inoltre, non gli servirebbe a nulla.</p>
<p>Capita così che il <em>novello programmatore C++</em> (nostro ormai noto compagno di avventure), conscio di questa convenzione, inizia a scrivere le sue classi con disinvoltura. Suddivide tutte le sue classi con cura ma pecca di solerzia: divide anche le <strong>classi template</strong>.</p>
<p>Le classi template sono delle classi che hanno uno (o più) tipi parametrizzati. Supponiamo infatti di voler scrivere una struttura dati (ad esempio un array)per organizzare <em>Pere</em>.<em> </em>Poi decidiamo di scrivere una struttura dati analoga solo per gestire <em>Autoradio. </em>Ci rendiamo conto che la struttura fondamentale delle due classi è la stessa. Senza template dovremmo scrivere due classi differenti mentre con le classi template ci basta farne una parametrizzata. Vediamo un esempio:</p>
<pre>
<div class="codecolorer-container cpp dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">template</span> <br />
<span style="color: #0000ff;">class</span> MyArray<br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;std<span style="color: #008080;">::</span><span style="color: #007788;">vector</span> data<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">void</span> Add<span style="color: #008000;">&#40;</span>T &nbsp;<span style="color: #000040;">*</span>d<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">void</span> Remove<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #0000ff;">void</span> Print<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></div></div>
</pre>
<p>Come potete notare all&#8217;interno di questo scheletro di classe il tipo gestito non è esplicito ma indicato da un <em>segnaposto T</em>. Quando inizializziamo una nuova coda non ci resta che inizializzarla specificando il tipo parametrizzato, ad esempio in questo modo:</p>
<pre>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">MyArray&lt;Pere&gt; lista_pere = new MyArray&lt;Pere&gt;</div></div>
</pre>
<p>Ma come funziona questo artificio stregonesco? Molto semplice: in pratica è il compilatore che si incarica di scrivere le classi differenti basandosi sullo scheletro che voi avete dato.</p>
<p>Ed è proprio qui che cade la magagna! A causa di ciò, infatti, <strong>le classi template non possono essere divise in file .h e .cpp. </strong>se lo fate noterete che il vostro linker inizierà a lamentarsi vistosamente dicendovi che non esiste nessun <em>MyArray&lt;Pere&gt;.</em></p>
<p>Il motivo di questo comportamento è logico se ci pensate. Supponiamo di avere diviso il nostro template in due file: <em>MyArray.h </em>e <em>MyArray.cpp.<strong> </strong><span style="font-style: normal;">Supponiamo poi di utilizzare il nostro template nel file </span>Fruttivendolo.cpp</em>. A questo punto compiliamo:</p>
<ol>
<li>Compiliamo tranquillamente il nostro template generando il file compilato <em>MyArray.o.</em></li>
<li>A questo punto andiamo a compilare <em>Fruttivendolo.cpp</em>.</li>
<li>Come abbiamo detto prima il compilatore nota la riga
<pre><code class="codecolorer text dawn"><span class="text">MyArray&lt;Pere&gt;</span></code></pre>
<p> e quindi &#8220;costruisce&#8221; la classe corrispodente.</li>
<li><strong>Ma il file <em>Fruttivendolo.cpp</em> può vedere solo <em>MyArray.h </em>perché è il solo file incluso!</strong></li>
</ol>
<p>A questo punto il compilatore si porge giustamente la domanda: <strong>come faccio a compilare la classe MyArray&lt;Pere&gt; se non conosco come sono implementati i metodi del template MyArray.h?</strong></p>
<p>Infatti non lo fa. Ignora il tutto lasciando il compito al linker e sperando che esso trovi da qualche parte un aggancio ad una classe MyArray&lt;pere&gt; che, come è giusto che sia, non trova.</p>
<p>Come risolvere il problema? La soluzione più semplice è di scrivere tutto (dichiarazione più implementazione) tutto nel file header. Tuttavia noi vogliamo mantenere una certa omogeneità nel codice e vogliamo quindi mantenere la divisione!</p>
<p>Per questo ci sono tre soluzioni accettabili. Ovviamente ognuna hai suoi vantaggi e svantaggi e sta a voi scegliere quale sia la migliore per la vostra esigenza:</p>
<ol>
<li>Nel file .h aggiungere alla fine la riga <code class="codecolorer c dawn"><span class="c"><span style="color: #339933;">#include MyArray.cpp</span></span></code>. In questo modo viene simulata la scrittura &#8220;tutto in uno&#8221; pur mantenendo la suddivisione del file. <strong>Ovviamente in questo caso nel file .cpp NON VA INCLUSO IL FILE .h</strong> per evitare un inclusione ciclica. Questa soluzione ha lo svantaggio di &#8220;gonfiare&#8221; il codice compilato nel caso lo stesso template venga utilizzato in parecchi file.</li>
<li>Una soluzione alternativa è di definire tutte le funzioni come <em>inline</em>. Anche qui abbiamo gli stessi svantaggi del caso precedente (forse sono anche peggio).</li>
<li>La terza soluzione è l&#8217;ideale se sapete da subito quali sono i tipi di dato con cui utilizzerete il template. In questo caso vi basta aggiungere in fonfo al file .cpp la riga
<pre><code class="codecolorer cpp dawn"><span class="cpp"><span style="color: #0000ff;">template</span> <span style="color: #0000ff;">class</span> MyArray<span style="color: #000080;">&lt;</span>Pere<span style="color: #000080;">&gt;</span><span style="color: #008080;">;</span></span></code></pre>
<p> per forzare la compilazione del template per quei tipi particolari. A questo punto il linker troverà sicuramente una versione già compilate della classe che è stata appena chiamata.</li>
</ol>
<p>Spero che questa piccola note, spesso trascurata quando si parla di template, vi faccia risparmiare tutto il tempo che ha fatto perdere a me a suo tempo.</p>
<p>Buon coding! <img src='http://davideaversa.it/slashcode/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
 <p><a href="http://davideaversa.it/slashcode/?flattrss_redirect&amp;id=586&amp;md5=755dbf2988af440c1664d580b3f138ca" title="Flattr" target="_blank"><img src="http://davideaversa.it/slashcode/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://davideaversa.it/slashcode/2010/05/c-e-le-classi-template/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=thek3nger&amp;popout=1&amp;url=http%3A%2F%2Fdavideaversa.it%2Fslashcode%2F2010%2F05%2Fc-e-le-classi-template%2F&amp;language=it_IT&amp;category=text&amp;title=C%2B%2B+e+le+classi+template&amp;description=In+e+C%2FC%2B%2B+si+ha+la%C2%A0convenzione+di+suddividere+il+codice+all%26%238217%3Binterno+di+due+file%3A+i+file+.h+per+le+dichiarazioni+e+.cpp+o+.c.+Le+motivazioni+di+questa+scelta%2C+in...&amp;tags=C%2Ctemplate%2Cblog" type="text/html" />
	</item>
	</channel>
</rss>

